0

I was under the impression that the following is equivalent in Django:

qs = MyModel.objects.filter(some_field=123, another_field=456)

and

qs = MyModel.objects.filter(some_field=123).filter(another_field=456)

However, I did the following and it produces different results:

qs = Award.objects.filter(transaction__accepted=True)
if query_date: #assume date is given
    qs = qs.filter(transaction__date__lte=query_date)
summary = qs.annotate(total=Sum('transaction__units')) # gives incorrect answer - double counts

compared to this

qs = Award.objects.filter(transaction__accepted=True)
                          transaction__date__lte=query_date)
summary = qs.annotate(total=Sum('transaction__units')) 

In the top case it double counts the units. Does somebody know why this is the case? And is the general rule only use one filter together with annotate?

Below are my models.

class Award(models.Model):
    # some fields here


class Transaction(models.Model):
    units = models.IntergerField()
    date = models.DateField()
    award = models.ForeignKey(Award)
Kritz
  • 7,099
  • 12
  • 43
  • 73
  • I had similar problem, sadly I didn't figuered out reason, but added distinct helped: `qs.distinct().annotate(total=Sum('transaction__units'))` I recommend to read about [distinct in documentation](https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.distinct), before use – Daniel Barton Aug 19 '16 at 16:14
  • Not entirely sure if this is true but could the fact that you are running a filter on a query set that has already been returned be causing your problem? You said you didn't get double results when you put all your filters into one line right? I would venture a guess that it's the second filter inside your IF statement that is messing up? – Michael Platt Aug 19 '16 at 16:18
  • It is indeed the same issue, I guess annotate has nothing to do with it. It seems like if a filter spans multiple relationships you should put it in one filter otherwise the results are "OR-ed" – Kritz Aug 20 '16 at 07:51

0 Answers0