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)