﻿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
11293	Filters on aggregates lose connector	django@…	-	"When adding a filter on an aggregated column, it must be moved to the having clause instead of the where clause, but it loses the connector.  Using the model in the Aggregation help topic:


{{{
>>> print Book.objects.values('publisher').annotate(pub_books=Count('id')).filter(Q(pub_books__gt=10) | Q(pub_books=1)).query.as_sql()
('SELECT `having_test_book`.`publisher_id`, COUNT(`having_test_book`.`id`) AS `pub_books` FROM `having_test_book` GROUP BY `having_test_book`.`publisher_id` HAVING (COUNT(`having_test_book`.`id`) > %s  AND COUNT(`having_test_book`.`id`) = %s ) ORDER BY NULL', (10, 1))
}}}

The HAVING clause should be an OR, not an AND.  I think this happens because django.db.models.sql.query add_filter treats each filter individually.  

A more complicated case that also needs to be handled is a filter that involves OR connectors as well as mixed aggregate and non-aggregate columns:

{{{
>>> print Book.objects.values('publisher').annotate(pub_books=Count('id')).filter(Q(pub_books__gt=10) | Q(pages=1)).query.as_sql()
('SELECT `having_test_book`.`publisher_id`, COUNT(`having_test_book`.`id`) AS `pub_books` FROM `having_test_book` WHERE `having_test_book`.`pages` = %s  GROUP BY `having_test_book`.`publisher_id` HAVING COUNT(`having_test_book`.`id`) > %s  ORDER BY NULL', (1, 10))
}}}

One filter ends up in WHERE, and the other in HAVING, but both need to be moved to HAVING for the connector to work."	Bug	closed	Database layer (models, ORM)	1.4	Normal	fixed	having, where, aggregate, connector, annotate	jay.wineinger@… gz eallik@… bas@… ego@… uwe+django@…	Accepted	1	0	0	0	0	0
