#6422: Support for 'DISTINCT ON' queries with QuerySet.distinct() -------------------------------------+------------------------------------- Reporter: Manfred | Owner: jgelens Wassmann <manolo@…> | Status: assigned Type: New | Component: Database layer feature | (models, ORM) Milestone: | Severity: Normal Version: SVN | Keywords: dceu2011 Resolution: | Has patch: 1 Triage Stage: Accepted | Needs tests: 0 Needs documentation: 0 | Easy pickings: 0 Patch needs improvement: 0 | UI/UX: 0 | -------------------------------------+------------------------------------- Changes (by jgelens):
* needs_better_patch: 1 => 0 Comment: The 'parent' is an foreign key to self. When you print the query you'll see it doesn't add the parent_id to the ORDER BY clause: {{{ >>> print Tag.objects.all().order_by('parent').query SELECT "queries_tag"."id", "queries_tag"."name", "queries_tag"."parent_id", "queries_tag"."category_id" FROM "queries_tag" LEFT OUTER JOIN "queries_tag" T2 ON ("queries_tag"."parent_id" = T2."id") ORDER BY T2."name" ASC }}} The DISTINCT ON expression requires the leftmost ORDER BY to match the fields given in the DISTINCT ON clause. To make sure the parent_id will be in ORDER BY, use parent__pk or parent__id: {{{ >>> print Tag.objects.all().order_by('parent__pk').query SELECT "queries_tag"."id", "queries_tag"."name", "queries_tag"."parent_id", "queries_tag"."category_id" FROM "queries_tag" LEFT OUTER JOIN "queries_tag" T2 ON ("queries_tag"."parent_id" = T2."id") ORDER BY "queries_tag"."parent_id" ASC }}} Now if you update your ORM call a lil, you'll get the expected results: {{{ >>> print Tag.objects.distinct('parent').order_by('parent__pk') [<Tag: t3>, <Tag: t5>, <Tag: t1>] }}} I added a note to the documentation about the 'order_by' requirement. It's not a bug, so I hope the documentation is more clear now. -- Ticket URL: <https://code.djangoproject.com/ticket/6422#comment:37> 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 this group at http://groups.google.com/group/django-updates?hl=en.