Re: [Django] #35958: QuerySet.distinct() crashes with "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"

3 views
Skip to first unread message

Django

unread,
Dec 1, 2024, 7:50:11 PM12/1/24
to django-...@googlegroups.com
#35958: QuerySet.distinct() crashes with "SELECT DISTINCT ON expressions must match
initial ORDER BY expressions"
-------------------------------------+-------------------------------------
Reporter: adofosam | Owner: (none)
Type: Bug | Status: closed
Component: Database layer | Version: 5.1
(models, ORM) | Resolution:
Severity: Normal | worksforme
Keywords: distinct | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by Simon Charette):

* resolution: => worksforme
* status: new => closed

Comment:

I cannot reproduce the models you've provided (assuming you meant
`EventList` in your report and not `List`)

{{{#!python
# models.py
import uuid

from django.db import models


class User(models.Model):
pass


class EventList(models.Model):
id = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False, unique=True
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
email = models.EmailField()

# tests.py
from django.test import TestCase

from .models import EventList, User


class FooTests(TestCase):
def test_bar(self):
user = User.objects.create()
list(EventList.objects.filter(user=user).order_by("email").distinct("email"))
}}}

the resulting SQL

{{{#sql
SELECT DISTINCT ON ("lists_eventlist"."email") "lists_eventlist"."id",
"lists_eventlist"."user_id",
"lists_eventlist"."email"
FROM "lists_eventlist"
WHERE "lists_eventlist"."user_id" = 1
ORDER BY "lists_eventlist"."email" ASC;
}}}

Something appears to be missing from your report and judging from your
report it has something to do with the `order_by` specified prior to
`distinct`.
--
Ticket URL: <https://code.djangoproject.com/ticket/35958#comment:2>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Reply all
Reply to author
Forward
0 new messages