Opened 5 years ago

Closed 5 years ago

#30518 closed Bug (duplicate)

Multiple Count annotation with filter doesn't work properly.

Reported by: Roman Krejčík Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: annotate
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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))
)

Change History (1)

comment:1 by Mariusz Felisiak, 5 years ago

Resolution: duplicate
Status: newclosed
Summary: Multiple Count annotation with filter doesn't work properly (at least if related modelas has same named fileds)Multiple Count annotation with filter doesn't work properly.
Version: 2.2master

Duplicate of #10060 (see documentation).

Note: See TracTickets for help on using tickets.
Back to Top