stinkypyper
stinkypyper

Reputation: 2098

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

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.

Upvotes: 4

Views: 4141

Answers (2)

Will Hardy
Will Hardy

Reputation: 14846

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.

Upvotes: 13

ariddell
ariddell

Reputation: 3423

If null=True is specified for the field you should be able to do an Instance.<foreignmodel>_set.clear() I might be off on this..

Upvotes: 1

Related Questions