Opened 16 hours ago

Last modified 7 hours ago

#36648 new Bug

"pk" exception when using first() on unordered queryset with aggregation does not consider composite pk fields provided separately

Reported by: Jacob Walls Owned by:
Component: Database layer (models, ORM) Version: 5.2
Severity: Release blocker Keywords: compositepk
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Discovered while poking into the source for first() that we have a special case for "pk" that does not behave equivalently for composite primary key fields specified individually.

A test for CompositePKAggregateTests:

The commented out assertion shows the point of the guard -- it should raise a TypeError in most cases of using first() on an unordered queryset, see #33772.

The second assertion shows the exception for values("pk") -- this does not raise.
The third assertion tries to provide the values for a composite pk separately -- this should not raise...

    def test_group_by_guard(self):
        # This assertion passes, only included to demonstrate the behavior.
        # with self.assertRaises(TypeError):
        #     Comment.objects.values("text").annotate(max=Max("id")).first()
        Comment.objects.values("pk").annotate(max=Max("id")).first()  # passes
        Comment.objects.values("tenant", "id").annotate(max=Max("id")).first()  # fails

... but does:

TypeError: Cannot use QuerySet.first() on an unordered queryset performing aggregation. Add an ordering with order_by().

Change History (2)

comment:1 by Natalia Bidart, 7 hours ago

Keywords: compositepk added
Triage Stage: UnreviewedAccepted

comment:2 by Natalia Bidart, 7 hours ago

Summary: "pk" exception from guard against using first() on unordered queryset with aggregation does not consider composite pk fields provided separately"pk" exception when using first() on unordered queryset with aggregation does not consider composite pk fields provided separately
Note: See TracTickets for help on using tickets.
Back to Top