#29214: Invalid SQL generated when annotating a subquery with an outerref to an
annotated field.
-------------------------------------+-------------------------------------
Reporter: Oskar Persson | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: master
(models, ORM) |
Severity: Normal | Resolution:
Keywords: queryset | Triage Stage: Accepted
annotations |
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):
Thanks!
Something suspicious here is the usage of `F('parent__link')` which should
be disallowed per https://code.djangoproject.com/ticket/14104#comment:1.
We don't support `JOIN`s in `UPDATE` unless I'm mistaken so I suspect the
`JOIN`'ed `T2` table is simply get pruned by `SQLUpdateCompiler`.
The only way to add support for such query would be to make
`OuterRef('parent__link')` result in a `JOIN` within the subquery, notice
how the `filter(parent__isnull=False)` predicate results in a subquery
instead of an `INNER JOIN` like it does when `.update` is not used in
comment:9.
I assume we'd want do something similar for `OuterRef` that include a `__`
so the resulting query is
{{{#!python
latest_parent =
Recursive.objects.filter(link=OuterRef('parent__link')).order_by('id')
Recursive.objects.filter(
parent__isnull=False
).update(parent_id=Subquery(latest_parent.values('pk')[:1])
}}}
{{{#!sql
UPDATE "recursive_model"
SET "parent_id" = (
SELECT U0."id"
FROM "recursive_model" U0
WHERE U0."link" IN (
SELECT U1."link"
FROM "recursive_model" U1
WHERE U1."id" = "recursive_model"."parent_id"
)
ORDER BY U0."id" ASC
LIMIT 1
)
WHERE "recursive_model"."id" IN (
SELECT V0."id"
FROM "recursive_model" V0
INNER JOIN "recursive_model" V1
ON (V0."parent_id" = V1."id")
WHERE V0."parent_id" IS NOT NULL
)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/29214#comment:12>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/070.39fea7df4ff92649ad19d129d7e5b5de%40djangoproject.com.