#30894: Reverse OneToOneField relation: `prefetch_related` uses `related_name`
while `select_related` uses `related_query_name`
-------------------------------------+-------------------------------------
               Reporter:  Adam       |          Owner:  nobody
  Sołtysik                           |
                   Type:  Bug        |         Status:  new
              Component:  Database   |        Version:  2.2
  layer (models, ORM)                |
               Severity:  Normal     |       Keywords:
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 The documentation
 (https://docs.djangoproject.com/en/2.2/ref/models/querysets/#select-
 related) states:

   You can also refer to the reverse direction of a OneToOneField in the
 list of fields passed to select_related — that is, you can traverse a
 OneToOneField back to the object on which the field is defined. Instead of
 specifying the field name, use the related_name for the field on the
 related object.

 But in fact `related_query_name` is used by `select_related` and
 `related_name` is used by `prefetch_related` .

 When we have the following models:

 {{{
 class A(Model):
     pass
 }}}
 {{{
 class B(Model):
     a = OneToOneField('A', related_name='b_set', related_query_name='b')
 }}}

 then `a.select_related('b')` works and `a.prefetch_related('b')` does not:

 {{{AttributeError: Cannot find 'b' on A object, 'b' is an invalid
 parameter to prefetch_related()}}}

 or if class `A` happens to have a property named `b`:

 {{{ValueError: 'b' does not resolve to an item that supports prefetching -
 this is an invalid parameter to prefetch_related().}}}

 And vice versa, `a.prefetch_related('b_set')` works and
 `a.select_related('b_set')` does not:

 {{{django.core.exceptions.FieldError: Invalid field name(s) given in
 select_related: 'b_set'. Choices are: b}}}

 The documentation implies that both methods should use `related_name`, but
 I think it would be more intuitive if both used `related_query_name`,
 given that we can write lookups like in filter queries etc., and such a
 change would probably be less backward-incompatible.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/30894>
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/050.36f6257cfdfa7c555f215e655bf9a533%40djangoproject.com.

Reply via email to