Opened 2 months ago

Last modified 2 months ago

#35741 closed New feature

Checking for whether a reverse OneToOne relation works is ugly — at Initial Version

Reported by: Chase Adams Owned by:
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: OneToOne
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The official docs suggest this methodology for checking if a reverse OneToOne relation exists:

>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
...     p2.restaurant
... except ObjectDoesNotExist:
...     print("There is no restaurant here.")
...
There is no restaurant here.

( https://docs.djangoproject.com/en/5.1/topics/db/examples/one_to_one/ )

This is verbose and not consistent with ForeignKey reverse relations, which always have the xxx_set present on models with reverse FK relations.

This is an ancient issue that has been discussed a lot:
https://stackoverflow.com/questions/25944968/check-if-a-onetoone-relation-exists-in-django

But it still comes up because it isn't obvious that the reverse OneToOne field if the forward relationship does not exist.

Perhaps this has come up before, but I would suggest that a constant reverse relation field be added that allows the following syntax instead:

if not p2.restaurant
   print("There is no restaurant here.")

It would also be a good idea to enable assignment to the reverse OneToOne relation even when no relation exists:

p2.restaurant = p1.restaurant 
p2.save() # A DB transaction here that sets p1.restaurant.p to p2

That could also enable a small performance optimization in certain cases where p1 is loaded, but p1.restaurant is not, since p1 would have the id of p1.restaurant even when select_related is not used, and the ID could be used within the p2.save() transaction instead of having two separate transactions in the alternative below:

p1.restaurant.p = p2 # One transaction here to look up .restaurant so .p can be accessed
p1.restaurant.save() # Another transaction here to save p1.restaurant.

While OneToOne is not as commonly used as other relations, I believe the verbosity and clunkiness of the current design would benefit from a refresh.

The main concept I'd suggest for informing a better design would be that both the forward and reverse relations should be symmetrical in usage. In other words, for anything you can do on the forward relationship (checking if it exists, assigning it, etc), the same is possible on the reverse. This would be more implicit with the idea of a "One to One" relationship, where structurally neither model is a parent but instead both models share a peer relationship, and peers should have equal capabilities.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top