Opened 9 years ago

Closed 9 years ago

#26633 closed Cleanup/optimization (duplicate)

OneToOneField's non-existence behaviour is inelegant

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

Description

Currently, if you have a model A with a nullable OneToOneField b_field to model B, and try to do:

a = A.objects.all()[0]  # Get a random object.
a.b_field

RelatedObjectDoesNotExist: Number has no allocation.

It is very inelegant to raise an exception in such a frequent use case as this, and doubly so when returning None is completely unambiguous. It makes writing elegant functional code very hard, as you have to break out of the string of functions to check whether this raised an exception.

Right now, if you want to check that the object's relation exists, you can do hasattr(a, "b_field"), which is rather unclean and, from what I understand, only works because hasattr swallows the exception, which is not the case in Python 3.2+.

I propose that the lookup has a try/except block internally and catches the RelatedObjectDoesNotExist exception there, returning None. I don't believe there will be any negative side-effects from this change, but code that expects an exception to be raised will need to be changed...

Change History (2)

comment:1 by Stavros Korokithakis, 9 years ago

One backwards-compatible solution to the exception raising problem would be to add a parameter on the field which, when True, would cause lookups to return None rather than raising an exception.

comment:2 by Tim Graham, 9 years ago

Resolution: duplicate
Status: newclosed
Type: UncategorizedCleanup/optimization

Duplicate of #10227, #3016, #11053

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