Aggregation on filter got the wrong result
Aggregation on complex filter logic will lead to faulty. I prepared a simple project to reproduct this fault. In this project, some of the following queries will get the wrong results:
> Tag.objects.distinct().filter(entries__when__year=2009).annotate(aggr = Count('entries'))
[<Tag: 1 aggr: 10>, <Tag: 2 aggr: 10>, <Tag: 3 aggr: 1>] # It's right
> Tag.objects.distinct().filter(entries__when__year=2009).annotate(aggr = Count('entries')).filter(entries__tags__token = '1').exclude(token='1')
[<Tag: 2 aggr: 100>, <Tag: 3 aggr: 1>] # Ooops, it's wrong.
> Tag.objects.distinct().filter(entries__when__year=2009).filter(entries__tags__token = '1').exclude(token='1').annotate(aggr = Count('entries'))
[<Tag: 2 aggr: 100>, <Tag: 3 aggr: 1>] # the same wrong result
# let's try Sum
> Tag.objects.distinct().filter(entries__when__year=2009).annotate(aggr = Sum('entries__visits'))
[<Tag: 1 aggr: 55>, <Tag: 2 aggr: 55>, <Tag: 3 aggr: 1>] # It's OK
> Tag.objects.distinct().filter(entries__when__year=2009).filter(entries__tags__token = '1').exclude(token='1').annotate(aggr = Sum('entries__visits'))
[<Tag: 2 aggr: 550>, <Tag: 3 aggr: 1>] # wrong
a simple project to reproduce the fault