Search code examples
pythondjangodjango-modelsdjango-viewsdjango-orm

Key (id)=() is still referenced from table for onetoone field


I have 1 to 1 field in my model where i would still need to link the data with other while i delete them on the other table.In my view i am deleting model 2 instance while that is deleted i am setting the completed to Tue but it is throwing error.

models.py

class Model1(models.Model):
    model_2_attribute = models.OnetoOneField('Model2' on_delete=models.DO_NOTHING)
    completed = model.BooleanField(default=False)

Solution

  • There's missing a default value or the option for the model_2_attribute to be null. If you delete Model2 then Model1 would have an invalid relation.

    Option 1 would be to set the default value to null. If you delete Model2 then the model_2_attribute will be None.

    class Model1(models.Model):
        model_2_attribute = models.OneToOneField('Model2', on_delete=models.SET_NULL, blank=True, null=True)
    

    Option 2 would be to move the completed field into Model2 and do not delete it. Instead only set the field to True.

    class Model1(models.Model):
        model_2_attribute = models.OneToOneField('Model2', on_delete=models.DO_NOTHING)
    
    class Model2(models.Model):
        # your fields
        completed = model.BooleanField(default=False)
    

    You can then filter for non-completed objects like:

    qs = Model1.objects.filter(model_2_attribute__completed=False)