Setting both sides of OneToOne field using the related_name on a serializer

I am gonna call source the model that has the OneToOne field defined in it.
I am gonna call target the model that is referenced by the OneToOne field, so, it has the related_name in it.

So this way if i have a OneToOne field called “relation” in the source with a related name “reverse_relation” i expect to have:
source.relation == target
target.reverse_relation == source

In a project im making i have a TargetSerializer with a “reverse_relation” field, when i create an instance of target in a view and check the value of self.reverse_relation in the target.save() method, i have the value ‘source’

but after i return to the view if i test the value of source.relation, i have ‘None’

is this a bug? Or am i missing something?

It sounds like you may have already fetched the instance of source from the DB in the view before saving the target and creating the relationship. If you were to refetch it after you save target, it would reflect what’s in the database. Or you can use source.refresh_from_db().

1 Like

Loved your answer caused that is exactly what was happening, i was calling source.save() in the last lines of the view and as this source was the one i got from the database before creating the target it would overwrite the relation with ‘None’, now i call target.reverse_relation.save() in the last lines of view and everything seems all right after i leave the view.

I tested the refresh_from_db() and source.relation is empty afterwards, i read a little bit of the documentation and thought maybe it had something to do with this being a relation and not a simple field in the table, but i dont understand too much about this yet