#25081: QuerySet.get() ignores order_by in DISTINCT ON queries
----------------------------------------------+--------------------
     Reporter:  pdewacht                      |      Owner:  nobody
         Type:  Bug                           |     Status:  new
    Component:  Database layer (models, ORM)  |    Version:  1.8
     Severity:  Normal                        |   Keywords:
 Triage Stage:  Unreviewed                    |  Has patch:  0
Easy pickings:  0                             |      UI/UX:  0
----------------------------------------------+--------------------
 The following query, using the PostgreSQL-specific DISTINCT ON, is
 mistranslated:

 {{{
 Model.objects.order_by('key', '-last_updated').distinct('key').get(key=x)
 }}}

 This generated this SQL query:

 {{{
 SELECT DISTINCT ON ("bug_mymodel"."key")
    "bug_mymodel"."id", "bug_mymodel"."key", "bug_mymodel"."last_updated",
 "bug_mymodel"."text"
 FROM "bug_mymodel"
 WHERE "bug_mymodel"."key" = 'xyz'
 }}}

 The ORDER BY request is omitted from the query, but DISTINCT ON is
 meaningless without sort order. Note that it is correct to use get() in
 this case, as it is guaranteed that there is only one result.

 We expected the following SQL:

 {{{
 SELECT DISTINCT ON ("bug_mymodel"."key")
    "bug_mymodel"."id", "bug_mymodel"."key", "bug_mymodel"."last_updated",
 "bug_mymodel"."text"
 FROM "bug_mymodel"
 WHERE "bug_mymodel"."key" = 'xyz'
 ORDER BY "bug_mymodel"."key" ASC, "bug_mymodel"."last_updated" DESC
 }}}

 Full test case:

 {{{
 class MyModel(models.Model):
     key     = models.CharField(max_length=100)
     last_updated = models.DateTimeField(auto_now=True)
     text         = models.CharField(max_length=100)

 def test():
     return MyModel.objects.order_by('key',
 '-last_updated').distinct('key').get(key='xyz')
 }}}

--
Ticket URL: <https://code.djangoproject.com/ticket/25081>
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/051.51999ffcfc8a468c64bf8f4cd080dcee%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to