Save reverse OneToOne relations, possible fix for issue #5996 #7547
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR is an idea of how #5996 could be solved. It saves reverse relations in the
create
andupdate
methods ofModelSerializer
, as the serialized data with reverse OneToOne relations can give you the impression that the data was saved in the database while in fact it isn't.Example models and serializers (als included in the tests):
models:
serializers:
Now if you do something like:
When you would do this with plain Django models:
The reverse relation for the OneToOne field is not saved either. So this is default behaviour of Django, and debatable if this should be solved by DRF or not (ManyToMany relations get special treatment too, so OneToOne should be supported as well ?)
If this would not be something DRF should solve then the documentation could be extended to explain why this works as it works now and suggest a solution like overriding the save method of the specific model (or connect to the
post_save
signal) to save the reverse relation.