﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37402	AttributeError when calling first()/last() on an unordered queryset performing aggregation and grouping by an annotation	Jacob Walls	Django Sprints	"02eed4f37879b2077496f86bb1378a076b981233 (#36648) assumed all members of a `GROUP BY` were `Col`s. That introduced an `AttributeError` for cases involving a function output like `Lower`, shown here:

{{{#!py
from django.db import models
from django.db.models.functions import Lower

class Person(models.Model):
    name = models.CharField(max_length=100)

def run():
    # Should raise informative TypeError:
    # Cannot use QuerySet.first() on an unordered queryset performing aggregation.
    # Add an ordering with order_by().
    first = (
        Person.objects
        .values(""name"")
        .annotate(lower=Lower(""name""), count=models.Count(""id""))
        .first()
    )
}}}
{{{#!py
  File ""/usr/local/lib/python3.12/site-packages/django/db/models/query.py"", line 1187, in first
    self._check_ordering_first_last_queryset_aggregation(method=""first"")
  File ""/usr/local/lib/python3.12/site-packages/django/db/models/query.py"", line 2330, in _check_ordering_first_last_queryset_aggregation
    {col.target for col in self.query.group_by}
     ^^^^^^^^^^
AttributeError: 'Ref' object has no attribute 'target'
}}}

It's introduced in 5.2, but we could consider backporting to 6.1 as a ""crashing bug""."	Bug	assigned	Database layer (models, ORM)	5.2	Normal				Unreviewed	0	0	0	0	0	0
