Opened 3 weeks ago

Closed 2 weeks ago

Last modified 2 weeks ago

#35958 closed Bug (worksforme)

QuerySet.distinct() crashes with "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"

Reported by: adofosam Owned by:
Component: Database layer (models, ORM) Version: 5.1
Severity: Normal Keywords: distinct
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

When I attempt to run the following code, I get an error.

Code:

user = User.objects.get(id=user_id)
list = List.objects.filter(user=user).order_by('email').distinct('email')

Error (Context: my app is called "lists"):

django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("lists_list"...

I'm using a PostgreSQL database and my model is:

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()

Change History (2)

comment:1 by Tim Graham, 2 weeks ago

Description: modified (diff)
Summary: Issue with the distinct() function when specifying a field to run it onQuerySet.distinct() crashes with "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"

comment:2 by Simon Charette, 2 weeks ago

Resolution: worksforme
Status: newclosed

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

# 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

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 the error it has something to do with the order_by specified prior to distinct.

Last edited 2 weeks ago by Simon Charette (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top