[Django] #30518: Multiple Count annotation with filter doesn't work properly (at least if related modelas has same named fileds)

2 views
Skip to first unread message

Django

unread,
May 28, 2019, 5:00:23 AM5/28/19
to django-...@googlegroups.com
#30518: Multiple Count annotation with filter doesn't work properly (at least if
related modelas has same named fileds)
-------------------------------------+-------------------------------------
Reporter: farin | Owner: nobody
Type: Bug | Status: new
Component: Database | Version: 2.2
layer (models, ORM) |
Severity: Normal | Keywords: annotate
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
Lets have following models

{{{
class User(models.Model):
pass

class Subscription(models.Model):
user = models.ForeignKey(User, models.CASCADE)
valid_to = models.DateTimeField()

class SubscriptionToAuthor(models.Model):
user = models.ForeignKey(User, models.CASCADE)
valid_to = models.DateTimeField()
}}}

then annotate on only one related model works fine

{{{
# this is ok

User.objects.annotate(
subscribed_authors=Count('subscriptiontoauthor',
filter=Q(subscriptiontoauthor__valid_to__gt=now))
)
}}}

or
{{{
# this is ok

User.objects.annotate(
subscribed_newspapers=Count('subscription',
filter=Q(subscription__valid_to__gt=now))
)
}}}

but Count returns incorrect (too big) count numbers when both annotations
are used on single query set

{{{
# wrong result

User.objects.annotate(
subscribed_authors=Count('subscriptiontoauthor',
filter=Q(subscriptiontoauthor__valid_to__gt=now))
).annotate(
subscribed_newspapers=Count('subscription',
filter=Q(subscription__valid_to__gt=now))
)
}}}

--
Ticket URL: <https://code.djangoproject.com/ticket/30518>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
May 28, 2019, 5:08:46 AM5/28/19
to django-...@googlegroups.com
#30518: Multiple Count annotation with filter doesn't work properly.

-------------------------------------+-------------------------------------
Reporter: farin | Owner: nobody
Type: Bug | Status: closed
Component: Database layer | Version: master
(models, ORM) |
Severity: Normal | Resolution: duplicate
Keywords: annotate | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0

Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by felixxm):

* status: new => closed
* version: 2.2 => master
* resolution: => duplicate


Comment:

Duplicate of #10060 (see
[https://docs.djangoproject.com/en/stable/topics/db/aggregation
/#combining-multiple-aggregations documentation]).

--
Ticket URL: <https://code.djangoproject.com/ticket/30518#comment:1>

Reply all
Reply to author
Forward
0 new messages