﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
11945	Aggregation on filter got the wrong result	jay		"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
}}}"		closed	Database layer (models, ORM)	1.1		duplicate			Unreviewed	0	0	0	0	0	0
