Re: [Django] #37171: Targeting a subquery with __exact requires limiting to one result even when wrapped by explicit Subquery (was: Query that worked in Django 5.x now throws error: "The QuerySet value for an exact lookup must be limited to one result using slicing")

5 views
Skip to first unread message

Django

unread,
Jun 15, 2026, 3:08:31 PMJun 15
to django-...@googlegroups.com
#37171: Targeting a subquery with __exact requires limiting to one result even when
wrapped by explicit Subquery
-------------------------------------+-------------------------------------
Reporter: Mark Baird | Owner: (none)
Type: Bug | Status: closed
Component: Database layer | Version: 6.0
(models, ORM) |
Severity: Normal | Resolution: invalid
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by Jacob Walls):

* resolution: => invalid
* status: new => closed
* summary:
Query that worked in Django 5.x now throws error: "The QuerySet value
for an exact lookup must be limited to one result using slicing"
=>
Targeting a subquery with __exact requires limiting to one result even
when wrapped by explicit Subquery

Comment:

Thanks for the report, we appreciate upgrade feedback.

That said, I think this is invalid. Notice you get the same error on
Django 5.2 if you remove the needless explicit `Subquery` wrapper, e.g.
`total_paid=subquery`. The fact that you could use an explicit wrapper to
evade the cardinality check is a bug we fixed in #36210, and indeed we had
to update some of our own tests to comply with the stricter test, see
de7bb7eab84dc53a7117127ad8eec44970efc509.

de7bb7eab84dc53a7117127ad8eec44970efc509 also shows what I think you need
to tweak: you should add `[:1]` to your subquery to slice only the first
result. If I am reading your query correctly, you are joining to a primary
key in a way that will ensure there is only one result, but the ORM has no
way of knowing that, so here you will have to be explicit.
--
Ticket URL: <https://code.djangoproject.com/ticket/37171#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
Reply all
Reply to author
Forward
0 new messages