#25171: Can't update queryset after Count annotation
-------------------------------------+-------------------------------------
Reporter: fraserharris | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 1.6
(models, ORM) |
Severity: Normal | Resolution:
Keywords: queryset, update, | Triage Stage: Accepted
annotate, count |
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by jarshwah):
The query that would work in the above situation (aggregate, filter,
update) would be roughly:
{{{
update category
set used=true
where id in (
select X.id
from (select id, COUNT(tiles_id) tile_count from category group by id)
X
where X.tile_count >= 0
)
-- OR preferably?
update category
set used=true
where id in (
select id tile_count from category group by id
having COUNT(tiles_id) > 0
)
}}}
Which I think can be generated with roughly the following ORM code (not
tested):
{{{
inner =
Category.objects.all().annotate(tiles_count=Count("tiles")).filter(tiles_count__gt=0)
# maybe inner = inner.values('pk') ?
Category.objects.filter(pk__in=inner).update(used=True)
}}}
It might be possible to get SQLUpdateCompiler to detect annotations, and
then create a new queryset, passing the existing queryset as an argument
to `pk__in=previous`. Or teach it to drop anything from the subquerys
`annotations_select` but ensure it stills GROUPs and HAVINGs.
--
Ticket URL: <https://code.djangoproject.com/ticket/25171#comment:7>
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 post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/070.0ce47728d842e0da8088a738727e5e72%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.