#24254: Passing a query to "pk__in" of another query may result in invalid SQL
-------------------------------------+-------------------------------------
     Reporter:  bronger              |                    Owner:  nobody
         Type:  Bug                  |                   Status:  new
    Component:  Database layer       |                  Version:  1.7
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by inglesp):

 * needs_better_patch:   => 0
 * needs_tests:   => 0
 * needs_docs:   => 0


Comment:

 Have had a little dig into this.

 Consider an `__in` lookup with the following on the RHS:
 `M.objects.order_by(sort_field).distinct()[m:n]`.

 This generates a query that returns both `M`'s primary key and
 `sort_field`.  Because it returns two fields, it cannot be used as a
 subquery (at least in SQLite) and so we hit the reported error.

 I think this behaviour is related to a
 
[https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct
 warning in the docs]: "Any fields used in an `order_by()` call are
 included in the SQL `SELECT` columns" (although from reading the code for
 `SQLCompiler.get_extra_select` I think that the fields used in an
 `order_by()` call are only included in the `SELECT` columns when the query
 has `distinct` set).

 It's not obvious to me why any fields used in an `order_by()` call
 '''must''' always be included in the `SELECT` columns, so I'd like to
 propose a fix whereby `SQLCompiler.get_extra_select` returns an empty list
 if it's dealing with a subquery.  I've made that change locally, and
 nothing fails.  However, I don't know enough about the ORM to know whether
 this is a good idea!  I hope this is useful.

--
Ticket URL: <https://code.djangoproject.com/ticket/24254#comment:1>
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/065.63b93f9b930942b1868bbb5d292b4606%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to