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
JavaScript
x
4
1
class Model1(models.Model):
2
model_2_attribute = models.OnetoOneField('Model2' on_delete=models.DO_NOTHING)
3
completed = model.BooleanField(default=False)
4
Advertisement
Answer
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.
JavaScript
1
3
1
class Model1(models.Model):
2
model_2_attribute = models.OneToOneField('Model2', on_delete=models.SET_NULL, blank=True, null=True)
3
Option 2 would be to move the completed
field into Model2
and do not delete it. Instead only set the field to True.
JavaScript
1
7
1
class Model1(models.Model):
2
model_2_attribute = models.OneToOneField('Model2', on_delete=models.DO_NOTHING)
3
4
class Model2(models.Model):
5
# your fields
6
completed = model.BooleanField(default=False)
7
You can then filter for non-completed objects like:
JavaScript
1
2
1
qs = Model1.objects.filter(model_2_attribute__completed=False)
2