Home > OS >  How to set another instance as foreign key on delete in django?
How to set another instance as foreign key on delete in django?

Time:08-29

so if I have a "company" model and a "person" model, and the "company" model has an owner ( a "person" model instance), and a co-owner( a "person" model instance too), I want to make it so that when the owner is deleted the co-owner becomes the owner and the co-owner becomes empty, is that possible in Django?

CodePudding user response:

Yes it is possible. You could for example override the delete method:

class Company(models.Model):
    owner = models.ForeignKey(
        Person,
        null=True,
        on_delete=models.SET_NULL,
        related_name='owned_companies'
    )

    co_owner = models.ForeignKey(
        Person,
        null=True,
        on_delete=models.SET_NULL,
        related_name='co_owned_companies'
    ) 


class Person(models.Model):
    # fields and stuff...

    def delete(self, *args, **kwargs):
        for company in self.owned_companies.all():
            company.owner = company.co_owner
            company.co_owner = None
            company.save()
        super(Person, self).delete(*args, **kwargs)

Written from mind, maybe on_delete must be models.DO_NOTHING on Company.owner, not sure. But it should generally work.

This won't work with bulk functions. If you want to use djangos bulk functions you need to register a pre delete signal as an alternative method.

CodePudding user response:

What you can do is override the delete method in the Person model so it changes the owner of the Company to the co-owner. Once this change is made it will then delete the Person.

class Company(model.Models):
    owner = models.ForeignKey(Person, null=True, on_delete=DO_NOTHING)
    co_owner = models.ForeignKey(Person, null=True, on_delete=SET_NULL)

class Person(models.Model):
    #Person model stuff here

    def delete(self):
        companies = Company.objects.filter(owner=self)
        
        for company in companies:
            company.owner = company.co_owner
            company.owner = None
            company.save()
            super(Person, self).delete()
  • Related