#10227: Support a related_default on OneToOne fields
-------------------------------------+-------------------------------------
     Reporter:  rvdrijst             |                    Owner:  nobody
         Type:  New feature          |                   Status:  new
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |               Resolution:
     Severity:  Normal               |             Triage Stage:  Accepted
     Keywords:  onetoone related     |      Needs documentation:  0
  expection null                     |  Patch needs improvement:  0
    Has patch:  0                    |                    UI/UX:  0
  Needs tests:  0                    |
Easy pickings:  0                    |
-------------------------------------+-------------------------------------

Comment (by akaariai):

 The example of related_default usage is exactly what I am afraid. That
 code contains a serious pitfall: the user.profile isn't saved, and it will
 not be associated to the user if you don't save it. And, you do get that
 default value even for saved user instances.

 There is a big difference to how foreign key default argument works:
 {{{
 class A(models.Model):
     pass

 def get_a():
     return A.objects.get_or_create(pk=1)[0]

 class B(models.Model):
     a = models.ForeignKey(A, null=True, default=get_a)

 b = B()
 print b.a
 b = B(a=None)
 print b.a
 b = B(a=None)
 b.save()
 b = B.objects.get()
 print b.a
 }}}

 The output is:
 {{{
 A object
 None
 None
 }}}

 My understanding is that the "related_default" would return "A object" for
 each case. This is broken - what you get from b.a doesn't reflect the
 database state.

 The related_none could work. Here I am mainly worried of not knowing what
 happens when I write:
 {{{
 p = request.user.profile
 }}}
 does it raise `DoesNotExist` if the profile doesn't exists, or will p just
 be None? However, I do not feel too strongly about this case.

 The good thing about b.nget('a') is that when you see the code, you
 immediately know what the code does. You are explicitly asking for a value
 that can be None value, so you will be prepared to handle the None case.
 This is relatively simple to do in user code, so there is no strong reason
 to have this convenience method in Django core.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/10227#comment:26>
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 post to this group, send email to django-updates@googlegroups.com.
To unsubscribe from this group, send email to 
django-updates+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to