Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do I clear a one to one relationship in a Django model?

Tags:

django

I am using a one to one relationship between two models and I need to be able to clear that relationship. However, I cannot find a way to clear(clear(), remove(), etc...) it to remove that relationship, and the Django admin will not perform that operation. Does anyone have experience with this problem? I think I may have to skip the one to one field and use a one to many with unique=true set on the field.

Edit: I should have mentioned. I do have null=True set on the field, but it does not make a difference.

like image 846
stinkypyper Avatar asked Dec 17 '22 03:12

stinkypyper


1 Answers

just set it to None and save :-)

my_instance.my_one_to_one_fieldname = None
my_instance.save()

edit: By the way, this only works for the model that you defined the OneToOneField on. I'm not sure how you would go about doing this backwards, except for:

my_related_instance.othermodel.my_one_to_one_fieldname = None
my_related_instance.othermodel.save()

But that's just the same as doing:

my_instance = my_related_instance.othermodel

and then continuing like the first example.

like image 77
Will Hardy Avatar answered Mar 07 '23 01:03

Will Hardy