Opened 16 years ago
Closed 2 years ago
#10621 closed New feature (duplicate)
Add a way to have an aggregate() result as a queryset
Reported by: | Malcolm Tredinnick | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
If one is trying to construct a complex queryset, involving nesting other querysets, there's currently no way to include the results of an aggregate()
call. For example, consider
class Item(models.Model): name = models.CharField(max_length=10)
If I want to include the number of Items in some other queryset, such as
Foo.objects.filter(items__in=[...]).annotate(num=Count("items").filter(num=item_count)
We can't write item_count (which would be Items.objects.aggregate(Count("id"))
) as an inner queryset here, since the aggregate()
call returns a dictionary, not a queryset.
The return value of aggregate()
is fine, but this ticket is about adding a version that does return a queryset. Right now, there's no way to fake this with annotate(...).values(...)
since that always introduces a GROUP BY
clause and the whole point is not to group by anything.
Not sure whether adding a parameter to aggregate()
is the right idea, or adding something to the annotate()
route to specify "no grouping whatsoever". This is all 1.2 timeframe stuff, but it's something to think about.
Change History (8)
comment:1 by , 16 years ago
milestone: | → 1.2 |
---|---|
Triage Stage: | Unreviewed → Accepted |
comment:2 by , 15 years ago
comment:3 by , 15 years ago
Hmm, my statements above are patently false (you can do that with HAVING). Forget I ever said anything.
comment:4 by , 15 years ago
milestone: | 1.2 |
---|
1.2 is feature-frozen, moving this feature request off the milestone.
comment:5 by , 14 years ago
Severity: | → Normal |
---|---|
Type: | → New feature |
comment:8 by , 2 years ago
Resolution: | → duplicate |
---|---|
Status: | new → closed |
#28296 is a duplicate which happens to have more up-to-date discussion and and associated patch so I'll close this one as a duplicate.
Maybe I misunderstand the problem, but in (postgre)SQL there is no way to filter on an aggregate column, e.g.:
You can ORDER BY aggregate columns (so perhaps this idea is still useful) but I'm not sure it'll work with .filter(num=item_count)