tags:

views:

54

answers:

1

If we set up a profile how Django recommends:

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)

Then when you delete the User object from Django admin, it deletes his profile too.This is because the profile has a foreign key to user and it wants to protect referential integrity. However, I want this functionality even if the pointer is going the other way. For example, on my Profile class I have:

shipper = models.ForeignKey(Shipper, unique=True, blank=True, null=True)
carrier = models.ForeignKey(Carrier, unique=True, blank=True, null=True)
affiliat = models.ForeignKey(Affiliate, unique=True, blank=True, null=True, verbose_name='Affiliate')

And I want it so that if you delete the Profile it'll delete the associated shipper/carrier/affiliate objects (don't ask me why Django made "affiliate" some weird keyword). Because shippers, carriers and affiliates are types of users, and it doesn't make sense for them to exist without the rest of the data (no one would be able to log in as one).

The reason I didn't put the keys on the other objects, is because then Django would have to internally join all those tables every time I wanted to check which type the user was...

+1  A: 

You can override the delete() method of the Profile class and delete the other objects in this method before you delete the actual profile.

Something like:

class Profile(models.Model):
    # ...

    def delete(self):
        if self.shipper:
            self.shipper.delete()
        if self.carrier:
            self.carrier.delete()
        if self.affiliat:
            self.affiliat.delete()
        super(Profile, self).delete()
Felix Kling
Looks good, but the `delete()` method never seems to get called when I delete stuff through the Django admin...?
Mark
@Mark: It should at least work when you delete a single object. With deleting multiple objects there seems to be an issue: http://code.djangoproject.com/ticket/10751
Felix Kling