#26633: OneToOneField's non-existence behaviour is inelegant
----------------------------------------------+--------------------
     Reporter:  skorokithakis                 |      Owner:  nobody
         Type:  Uncategorized                 |     Status:  new
    Component:  Database layer (models, ORM)  |    Version:  1.9
     Severity:  Normal                        |   Keywords:
 Triage Stage:  Unreviewed                    |  Has patch:  0
Easy pickings:  0                             |      UI/UX:  0
----------------------------------------------+--------------------
 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...

--
Ticket URL: <https://code.djangoproject.com/ticket/26633>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/056.908912aac79ffeff59559901adc05a0a%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to