tests.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. from __future__ import absolute_import, unicode_literals
  2. import datetime
  3. import pickle
  4. from decimal import Decimal
  5. from operator import attrgetter
  6. from django.core.exceptions import FieldError
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F, Q
  9. from django.test import TestCase, Approximate, skipUnlessDBFeature
  10. from django.utils import six
  11. from django.utils.unittest import expectedFailure
  12. from .models import (Author, Book, Publisher, Clues, Entries, HardbackBook,
  13. ItemTag, WithManualPK)
  14. class AggregationTests(TestCase):
  15. fixtures = ["aggregation_regress.json"]
  16. def assertObjectAttrs(self, obj, **kwargs):
  17. for attr, value in six.iteritems(kwargs):
  18. self.assertEqual(getattr(obj, attr), value)
  19. def test_aggregates_in_where_clause(self):
  20. """
  21. Regression test for #12822: DatabaseError: aggregates not allowed in
  22. WHERE clause
  23. Tests that the subselect works and returns results equivalent to a
  24. query with the IDs listed.
  25. Before the corresponding fix for this bug, this test passed in 1.1 and
  26. failed in 1.2-beta (trunk).
  27. """
  28. qs = Book.objects.values('contact').annotate(Max('id'))
  29. qs = qs.order_by('contact').values_list('id__max', flat=True)
  30. # don't do anything with the queryset (qs) before including it as a
  31. # subquery
  32. books = Book.objects.order_by('id')
  33. qs1 = books.filter(id__in=qs)
  34. qs2 = books.filter(id__in=list(qs))
  35. self.assertEqual(list(qs1), list(qs2))
  36. def test_aggregates_in_where_clause_pre_eval(self):
  37. """
  38. Regression test for #12822: DatabaseError: aggregates not allowed in
  39. WHERE clause
  40. Same as the above test, but evaluates the queryset for the subquery
  41. before it's used as a subquery.
  42. Before the corresponding fix for this bug, this test failed in both
  43. 1.1 and 1.2-beta (trunk).
  44. """
  45. qs = Book.objects.values('contact').annotate(Max('id'))
  46. qs = qs.order_by('contact').values_list('id__max', flat=True)
  47. # force the queryset (qs) for the subquery to be evaluated in its
  48. # current state
  49. list(qs)
  50. books = Book.objects.order_by('id')
  51. qs1 = books.filter(id__in=qs)
  52. qs2 = books.filter(id__in=list(qs))
  53. self.assertEqual(list(qs1), list(qs2))
  54. @skipUnlessDBFeature('supports_subqueries_in_group_by')
  55. def test_annotate_with_extra(self):
  56. """
  57. Regression test for #11916: Extra params + aggregation creates
  58. incorrect SQL.
  59. """
  60. #oracle doesn't support subqueries in group by clause
  61. shortest_book_sql = """
  62. SELECT name
  63. FROM aggregation_regress_book b
  64. WHERE b.publisher_id = aggregation_regress_publisher.id
  65. ORDER BY b.pages
  66. LIMIT 1
  67. """
  68. # tests that this query does not raise a DatabaseError due to the full
  69. # subselect being (erroneously) added to the GROUP BY parameters
  70. qs = Publisher.objects.extra(select={
  71. 'name_of_shortest_book': shortest_book_sql,
  72. }).annotate(total_books=Count('book'))
  73. # force execution of the query
  74. list(qs)
  75. def test_aggregate(self):
  76. # Ordering requests are ignored
  77. self.assertEqual(
  78. Author.objects.order_by("name").aggregate(Avg("age")),
  79. {"age__avg": Approximate(37.444, places=1)}
  80. )
  81. # Implicit ordering is also ignored
  82. self.assertEqual(
  83. Book.objects.aggregate(Sum("pages")),
  84. {"pages__sum": 3703},
  85. )
  86. # Baseline results
  87. self.assertEqual(
  88. Book.objects.aggregate(Sum('pages'), Avg('pages')),
  89. {'pages__sum': 3703, 'pages__avg': Approximate(617.166, places=2)}
  90. )
  91. # Empty values query doesn't affect grouping or results
  92. self.assertEqual(
  93. Book.objects.values().aggregate(Sum('pages'), Avg('pages')),
  94. {'pages__sum': 3703, 'pages__avg': Approximate(617.166, places=2)}
  95. )
  96. # Aggregate overrides extra selected column
  97. self.assertEqual(
  98. Book.objects.extra(select={'price_per_page' : 'price / pages'}).aggregate(Sum('pages')),
  99. {'pages__sum': 3703}
  100. )
  101. def test_annotation(self):
  102. # Annotations get combined with extra select clauses
  103. obj = Book.objects.annotate(mean_auth_age=Avg("authors__age")).extra(select={"manufacture_cost": "price * .5"}).get(pk=2)
  104. self.assertObjectAttrs(obj,
  105. contact_id=3,
  106. id=2,
  107. isbn='067232959',
  108. mean_auth_age=45.0,
  109. name='Sams Teach Yourself Django in 24 Hours',
  110. pages=528,
  111. price=Decimal("23.09"),
  112. pubdate=datetime.date(2008, 3, 3),
  113. publisher_id=2,
  114. rating=3.0
  115. )
  116. # Different DB backends return different types for the extra select computation
  117. self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545'))
  118. # Order of the annotate/extra in the query doesn't matter
  119. obj = Book.objects.extra(select={'manufacture_cost' : 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2)
  120. self.assertObjectAttrs(obj,
  121. contact_id=3,
  122. id=2,
  123. isbn='067232959',
  124. mean_auth_age=45.0,
  125. name='Sams Teach Yourself Django in 24 Hours',
  126. pages=528,
  127. price=Decimal("23.09"),
  128. pubdate=datetime.date(2008, 3, 3),
  129. publisher_id=2,
  130. rating=3.0
  131. )
  132. # Different DB backends return different types for the extra select computation
  133. self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545'))
  134. # Values queries can be combined with annotate and extra
  135. obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).values().get(pk=2)
  136. manufacture_cost = obj['manufacture_cost']
  137. self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545'))
  138. del obj['manufacture_cost']
  139. self.assertEqual(obj, {
  140. "contact_id": 3,
  141. "id": 2,
  142. "isbn": "067232959",
  143. "mean_auth_age": 45.0,
  144. "name": "Sams Teach Yourself Django in 24 Hours",
  145. "pages": 528,
  146. "price": Decimal("23.09"),
  147. "pubdate": datetime.date(2008, 3, 3),
  148. "publisher_id": 2,
  149. "rating": 3.0,
  150. })
  151. # The order of the (empty) values, annotate and extra clauses doesn't
  152. # matter
  153. obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2)
  154. manufacture_cost = obj['manufacture_cost']
  155. self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545'))
  156. del obj['manufacture_cost']
  157. self.assertEqual(obj, {
  158. 'contact_id': 3,
  159. 'id': 2,
  160. 'isbn': '067232959',
  161. 'mean_auth_age': 45.0,
  162. 'name': 'Sams Teach Yourself Django in 24 Hours',
  163. 'pages': 528,
  164. 'price': Decimal("23.09"),
  165. 'pubdate': datetime.date(2008, 3, 3),
  166. 'publisher_id': 2,
  167. 'rating': 3.0
  168. })
  169. # If the annotation precedes the values clause, it won't be included
  170. # unless it is explicitly named
  171. obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name').get(pk=1)
  172. self.assertEqual(obj, {
  173. "name": 'The Definitive Guide to Django: Web Development Done Right',
  174. })
  175. obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name','mean_auth_age').get(pk=1)
  176. self.assertEqual(obj, {
  177. 'mean_auth_age': 34.5,
  178. 'name': 'The Definitive Guide to Django: Web Development Done Right',
  179. })
  180. # If an annotation isn't included in the values, it can still be used
  181. # in a filter
  182. qs = Book.objects.annotate(n_authors=Count('authors')).values('name').filter(n_authors__gt=2)
  183. self.assertQuerysetEqual(
  184. qs, [
  185. {"name": 'Python Web Development with Django'}
  186. ],
  187. lambda b: b,
  188. )
  189. # The annotations are added to values output if values() precedes
  190. # annotate()
  191. obj = Book.objects.values('name').annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).get(pk=1)
  192. self.assertEqual(obj, {
  193. 'mean_auth_age': 34.5,
  194. 'name': 'The Definitive Guide to Django: Web Development Done Right',
  195. })
  196. # Check that all of the objects are getting counted (allow_nulls) and
  197. # that values respects the amount of objects
  198. self.assertEqual(
  199. len(Author.objects.annotate(Avg('friends__age')).values()),
  200. 9
  201. )
  202. # Check that consecutive calls to annotate accumulate in the query
  203. qs = Book.objects.values('price').annotate(oldest=Max('authors__age')).order_by('oldest', 'price').annotate(Max('publisher__num_awards'))
  204. self.assertQuerysetEqual(
  205. qs, [
  206. {'price': Decimal("30"), 'oldest': 35, 'publisher__num_awards__max': 3},
  207. {'price': Decimal("29.69"), 'oldest': 37, 'publisher__num_awards__max': 7},
  208. {'price': Decimal("23.09"), 'oldest': 45, 'publisher__num_awards__max': 1},
  209. {'price': Decimal("75"), 'oldest': 57, 'publisher__num_awards__max': 9},
  210. {'price': Decimal("82.8"), 'oldest': 57, 'publisher__num_awards__max': 7}
  211. ],
  212. lambda b: b,
  213. )
  214. def test_aggrate_annotation(self):
  215. # Aggregates can be composed over annotations.
  216. # The return type is derived from the composed aggregate
  217. vals = Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors'))
  218. self.assertEqual(vals, {
  219. 'num_authors__sum': 10,
  220. 'num_authors__avg': Approximate(1.666, places=2),
  221. 'pages__max': 1132,
  222. 'price__max': Decimal("82.80")
  223. })
  224. def test_field_error(self):
  225. # Bad field requests in aggregates are caught and reported
  226. self.assertRaises(
  227. FieldError,
  228. lambda: Book.objects.all().aggregate(num_authors=Count('foo'))
  229. )
  230. self.assertRaises(
  231. FieldError,
  232. lambda: Book.objects.all().annotate(num_authors=Count('foo'))
  233. )
  234. self.assertRaises(
  235. FieldError,
  236. lambda: Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
  237. )
  238. def test_more(self):
  239. # Old-style count aggregations can be mixed with new-style
  240. self.assertEqual(
  241. Book.objects.annotate(num_authors=Count('authors')).count(),
  242. 6
  243. )
  244. # Non-ordinal, non-computed Aggregates over annotations correctly
  245. # inherit the annotation's internal type if the annotation is ordinal
  246. # or computed
  247. vals = Book.objects.annotate(num_authors=Count('authors')).aggregate(Max('num_authors'))
  248. self.assertEqual(
  249. vals,
  250. {'num_authors__max': 3}
  251. )
  252. vals = Publisher.objects.annotate(avg_price=Avg('book__price')).aggregate(Max('avg_price'))
  253. self.assertEqual(
  254. vals,
  255. {'avg_price__max': 75.0}
  256. )
  257. # Aliases are quoted to protected aliases that might be reserved names
  258. vals = Book.objects.aggregate(number=Max('pages'), select=Max('pages'))
  259. self.assertEqual(
  260. vals,
  261. {'number': 1132, 'select': 1132}
  262. )
  263. # Regression for #10064: select_related() plays nice with aggregates
  264. obj = Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0]
  265. self.assertEqual(obj, {
  266. 'contact_id': 8,
  267. 'id': 5,
  268. 'isbn': '013790395',
  269. 'name': 'Artificial Intelligence: A Modern Approach',
  270. 'num_authors': 2,
  271. 'pages': 1132,
  272. 'price': Decimal("82.8"),
  273. 'pubdate': datetime.date(1995, 1, 15),
  274. 'publisher_id': 3,
  275. 'rating': 4.0,
  276. })
  277. # Regression for #10010: exclude on an aggregate field is correctly
  278. # negated
  279. self.assertEqual(
  280. len(Book.objects.annotate(num_authors=Count('authors'))),
  281. 6
  282. )
  283. self.assertEqual(
  284. len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=2)),
  285. 1
  286. )
  287. self.assertEqual(
  288. len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__gt=2)),
  289. 5
  290. )
  291. self.assertEqual(
  292. len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__lt=3).exclude(num_authors__lt=2)),
  293. 2
  294. )
  295. self.assertEqual(
  296. len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__lt=2).filter(num_authors__lt=3)),
  297. 2
  298. )
  299. def test_aggregate_fexpr(self):
  300. # Aggregates can be used with F() expressions
  301. # ... where the F() is pushed into the HAVING clause
  302. qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
  303. self.assertQuerysetEqual(
  304. qs, [
  305. {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9},
  306. {'num_books': 2, 'name': 'Prentice Hall', 'num_awards': 7}
  307. ],
  308. lambda p: p,
  309. )
  310. qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
  311. self.assertQuerysetEqual(
  312. qs, [
  313. {'num_books': 2, 'name': 'Apress', 'num_awards': 3},
  314. {'num_books': 0, 'name': "Jonno's House of Books", 'num_awards': 0},
  315. {'num_books': 1, 'name': 'Sams', 'num_awards': 1}
  316. ],
  317. lambda p: p,
  318. )
  319. # ... and where the F() references an aggregate
  320. qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name','num_books','num_awards')
  321. self.assertQuerysetEqual(
  322. qs, [
  323. {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9},
  324. {'num_books': 2, 'name': 'Prentice Hall', 'num_awards': 7}
  325. ],
  326. lambda p: p,
  327. )
  328. qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards')
  329. self.assertQuerysetEqual(
  330. qs, [
  331. {'num_books': 2, 'name': 'Apress', 'num_awards': 3},
  332. {'num_books': 0, 'name': "Jonno's House of Books", 'num_awards': 0},
  333. {'num_books': 1, 'name': 'Sams', 'num_awards': 1}
  334. ],
  335. lambda p: p,
  336. )
  337. def test_db_col_table(self):
  338. # Tests on fields with non-default table and column names.
  339. qs = Clues.objects.values('EntryID__Entry').annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True))
  340. self.assertQuerysetEqual(qs, [])
  341. qs = Entries.objects.annotate(clue_count=Count('clues__ID'))
  342. self.assertQuerysetEqual(qs, [])
  343. def test_empty(self):
  344. # Regression for #10089: Check handling of empty result sets with
  345. # aggregates
  346. self.assertEqual(
  347. Book.objects.filter(id__in=[]).count(),
  348. 0
  349. )
  350. vals = Book.objects.filter(id__in=[]).aggregate(num_authors=Count('authors'), avg_authors=Avg('authors'), max_authors=Max('authors'), max_price=Max('price'), max_rating=Max('rating'))
  351. self.assertEqual(
  352. vals,
  353. {'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None}
  354. )
  355. qs = Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()
  356. self.assertQuerysetEqual(
  357. qs, [
  358. {'max_authors': None, 'name': "Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None}
  359. ],
  360. lambda p: p
  361. )
  362. def test_more_more(self):
  363. # Regression for #10113 - Fields mentioned in order_by() must be
  364. # included in the GROUP BY. This only becomes a problem when the
  365. # order_by introduces a new join.
  366. self.assertQuerysetEqual(
  367. Book.objects.annotate(num_authors=Count('authors')).order_by('publisher__name', 'name'), [
  368. "Practical Django Projects",
  369. "The Definitive Guide to Django: Web Development Done Right",
  370. "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
  371. "Artificial Intelligence: A Modern Approach",
  372. "Python Web Development with Django",
  373. "Sams Teach Yourself Django in 24 Hours",
  374. ],
  375. lambda b: b.name
  376. )
  377. # Regression for #10127 - Empty select_related() works with annotate
  378. qs = Book.objects.filter(rating__lt=4.5).select_related().annotate(Avg('authors__age'))
  379. self.assertQuerysetEqual(
  380. qs, [
  381. ('Artificial Intelligence: A Modern Approach', 51.5, 'Prentice Hall', 'Peter Norvig'),
  382. ('Practical Django Projects', 29.0, 'Apress', 'James Bennett'),
  383. ('Python Web Development with Django', Approximate(30.333, places=2), 'Prentice Hall', 'Jeffrey Forcier'),
  384. ('Sams Teach Yourself Django in 24 Hours', 45.0, 'Sams', 'Brad Dayley')
  385. ],
  386. lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name)
  387. )
  388. # Regression for #10132 - If the values() clause only mentioned extra
  389. # (select=) columns, those columns are used for grouping
  390. qs = Book.objects.extra(select={'pub':'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub')
  391. self.assertQuerysetEqual(
  392. qs, [
  393. {'pub': 1, 'id__count': 2},
  394. {'pub': 2, 'id__count': 1},
  395. {'pub': 3, 'id__count': 2},
  396. {'pub': 4, 'id__count': 1}
  397. ],
  398. lambda b: b
  399. )
  400. qs = Book.objects.extra(select={'pub':'publisher_id', 'foo':'pages'}).values('pub').annotate(Count('id')).order_by('pub')
  401. self.assertQuerysetEqual(
  402. qs, [
  403. {'pub': 1, 'id__count': 2},
  404. {'pub': 2, 'id__count': 1},
  405. {'pub': 3, 'id__count': 2},
  406. {'pub': 4, 'id__count': 1}
  407. ],
  408. lambda b: b
  409. )
  410. # Regression for #10182 - Queries with aggregate calls are correctly
  411. # realiased when used in a subquery
  412. ids = Book.objects.filter(pages__gt=100).annotate(n_authors=Count('authors')).filter(n_authors__gt=2).order_by('n_authors')
  413. self.assertQuerysetEqual(
  414. Book.objects.filter(id__in=ids), [
  415. "Python Web Development with Django",
  416. ],
  417. lambda b: b.name
  418. )
  419. # Regression for #15709 - Ensure each group_by field only exists once
  420. # per query
  421. qs = Book.objects.values('publisher').annotate(max_pages=Max('pages')).order_by()
  422. grouping, gb_params = qs.query.get_compiler(qs.db).get_grouping([], [])
  423. self.assertEqual(len(grouping), 1)
  424. def test_duplicate_alias(self):
  425. # Regression for #11256 - duplicating a default alias raises ValueError.
  426. self.assertRaises(ValueError, Book.objects.all().annotate, Avg('authors__age'), authors__age__avg=Avg('authors__age'))
  427. def test_field_name_conflict(self):
  428. # Regression for #11256 - providing an aggregate name that conflicts with a field name on the model raises ValueError
  429. self.assertRaises(ValueError, Author.objects.annotate, age=Avg('friends__age'))
  430. def test_m2m_name_conflict(self):
  431. # Regression for #11256 - providing an aggregate name that conflicts with an m2m name on the model raises ValueError
  432. self.assertRaises(ValueError, Author.objects.annotate, friends=Count('friends'))
  433. def test_values_queryset_non_conflict(self):
  434. # Regression for #14707 -- If you're using a values query set, some potential conflicts are avoided.
  435. # age is a field on Author, so it shouldn't be allowed as an aggregate.
  436. # But age isn't included in the ValuesQuerySet, so it is.
  437. results = Author.objects.values('name').annotate(age=Count('book_contact_set')).order_by('name')
  438. self.assertEqual(len(results), 9)
  439. self.assertEqual(results[0]['name'], 'Adrian Holovaty')
  440. self.assertEqual(results[0]['age'], 1)
  441. # Same problem, but aggregating over m2m fields
  442. results = Author.objects.values('name').annotate(age=Avg('friends__age')).order_by('name')
  443. self.assertEqual(len(results), 9)
  444. self.assertEqual(results[0]['name'], 'Adrian Holovaty')
  445. self.assertEqual(results[0]['age'], 32.0)
  446. # Same problem, but colliding with an m2m field
  447. results = Author.objects.values('name').annotate(friends=Count('friends')).order_by('name')
  448. self.assertEqual(len(results), 9)
  449. self.assertEqual(results[0]['name'], 'Adrian Holovaty')
  450. self.assertEqual(results[0]['friends'], 2)
  451. def test_reverse_relation_name_conflict(self):
  452. # Regression for #11256 - providing an aggregate name that conflicts with a reverse-related name on the model raises ValueError
  453. self.assertRaises(ValueError, Author.objects.annotate, book_contact_set=Avg('friends__age'))
  454. def test_pickle(self):
  455. # Regression for #10197 -- Queries with aggregates can be pickled.
  456. # First check that pickling is possible at all. No crash = success
  457. qs = Book.objects.annotate(num_authors=Count('authors'))
  458. pickle.dumps(qs)
  459. # Then check that the round trip works.
  460. query = qs.query.get_compiler(qs.db).as_sql()[0]
  461. qs2 = pickle.loads(pickle.dumps(qs))
  462. self.assertEqual(
  463. qs2.query.get_compiler(qs2.db).as_sql()[0],
  464. query,
  465. )
  466. def test_more_more_more(self):
  467. # Regression for #10199 - Aggregate calls clone the original query so
  468. # the original query can still be used
  469. books = Book.objects.all()
  470. books.aggregate(Avg("authors__age"))
  471. self.assertQuerysetEqual(
  472. books.all(), [
  473. 'Artificial Intelligence: A Modern Approach',
  474. 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp',
  475. 'Practical Django Projects',
  476. 'Python Web Development with Django',
  477. 'Sams Teach Yourself Django in 24 Hours',
  478. 'The Definitive Guide to Django: Web Development Done Right'
  479. ],
  480. lambda b: b.name
  481. )
  482. # Regression for #10248 - Annotations work with DateQuerySets
  483. qs = Book.objects.annotate(num_authors=Count('authors')).filter(num_authors=2).dates('pubdate', 'day')
  484. self.assertQuerysetEqual(
  485. qs, [
  486. datetime.date(1995, 1, 15),
  487. datetime.date(2007, 12, 6),
  488. ],
  489. lambda b: b
  490. )
  491. # Regression for #10290 - extra selects with parameters can be used for
  492. # grouping.
  493. qs = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'sheets' : '(pages + %s) / %s'}, select_params=[1, 2]).order_by('sheets').values('sheets')
  494. self.assertQuerysetEqual(
  495. qs, [
  496. 150,
  497. 175,
  498. 224,
  499. 264,
  500. 473,
  501. 566
  502. ],
  503. lambda b: int(b["sheets"])
  504. )
  505. # Regression for 10425 - annotations don't get in the way of a count()
  506. # clause
  507. self.assertEqual(
  508. Book.objects.values('publisher').annotate(Count('publisher')).count(),
  509. 4
  510. )
  511. self.assertEqual(
  512. Book.objects.annotate(Count('publisher')).values('publisher').count(),
  513. 6
  514. )
  515. publishers = Publisher.objects.filter(id__in=[1, 2])
  516. self.assertEqual(
  517. sorted(p.name for p in publishers),
  518. [
  519. "Apress",
  520. "Sams"
  521. ]
  522. )
  523. publishers = publishers.annotate(n_books=Count("book"))
  524. self.assertEqual(
  525. publishers[0].n_books,
  526. 2
  527. )
  528. self.assertEqual(
  529. sorted(p.name for p in publishers),
  530. [
  531. "Apress",
  532. "Sams"
  533. ]
  534. )
  535. books = Book.objects.filter(publisher__in=publishers)
  536. self.assertQuerysetEqual(
  537. books, [
  538. "Practical Django Projects",
  539. "Sams Teach Yourself Django in 24 Hours",
  540. "The Definitive Guide to Django: Web Development Done Right",
  541. ],
  542. lambda b: b.name
  543. )
  544. self.assertEqual(
  545. sorted(p.name for p in publishers),
  546. [
  547. "Apress",
  548. "Sams"
  549. ]
  550. )
  551. # Regression for 10666 - inherited fields work with annotations and
  552. # aggregations
  553. self.assertEqual(
  554. HardbackBook.objects.aggregate(n_pages=Sum('book_ptr__pages')),
  555. {'n_pages': 2078}
  556. )
  557. self.assertEqual(
  558. HardbackBook.objects.aggregate(n_pages=Sum('pages')),
  559. {'n_pages': 2078},
  560. )
  561. qs = HardbackBook.objects.annotate(n_authors=Count('book_ptr__authors')).values('name', 'n_authors')
  562. self.assertQuerysetEqual(
  563. qs, [
  564. {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'},
  565. {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'}
  566. ],
  567. lambda h: h
  568. )
  569. qs = HardbackBook.objects.annotate(n_authors=Count('authors')).values('name', 'n_authors')
  570. self.assertQuerysetEqual(
  571. qs, [
  572. {'n_authors': 2, 'name': 'Artificial Intelligence: A Modern Approach'},
  573. {'n_authors': 1, 'name': 'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'}
  574. ],
  575. lambda h: h,
  576. )
  577. # Regression for #10766 - Shouldn't be able to reference an aggregate
  578. # fields in an aggregate() call.
  579. self.assertRaises(
  580. FieldError,
  581. lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
  582. )
  583. def test_empty_filter_count(self):
  584. self.assertEqual(
  585. Author.objects.filter(id__in=[]).annotate(Count("friends")).count(),
  586. 0
  587. )
  588. def test_empty_filter_aggregate(self):
  589. self.assertEqual(
  590. Author.objects.filter(id__in=[]).annotate(Count("friends")).aggregate(Count("pk")),
  591. {"pk__count": None}
  592. )
  593. def test_none_call_before_aggregate(self):
  594. # Regression for #11789
  595. self.assertEqual(
  596. Author.objects.none().aggregate(Avg('age')),
  597. {'age__avg': None}
  598. )
  599. def test_annotate_and_join(self):
  600. self.assertEqual(
  601. Author.objects.annotate(c=Count("friends__name")).exclude(friends__name="Joe").count(),
  602. Author.objects.count()
  603. )
  604. def test_f_expression_annotation(self):
  605. # Books with less than 200 pages per author.
  606. qs = Book.objects.values("name").annotate(
  607. n_authors=Count("authors")
  608. ).filter(
  609. pages__lt=F("n_authors") * 200
  610. ).values_list("pk")
  611. self.assertQuerysetEqual(
  612. Book.objects.filter(pk__in=qs), [
  613. "Python Web Development with Django"
  614. ],
  615. attrgetter("name")
  616. )
  617. def test_values_annotate_values(self):
  618. qs = Book.objects.values("name").annotate(
  619. n_authors=Count("authors")
  620. ).values_list("pk", flat=True)
  621. self.assertEqual(list(qs), list(Book.objects.values_list("pk", flat=True)))
  622. def test_having_group_by(self):
  623. # Test that when a field occurs on the LHS of a HAVING clause that it
  624. # appears correctly in the GROUP BY clause
  625. qs = Book.objects.values_list("name").annotate(
  626. n_authors=Count("authors")
  627. ).filter(
  628. pages__gt=F("n_authors")
  629. ).values_list("name", flat=True)
  630. # Results should be the same, all Books have more pages than authors
  631. self.assertEqual(
  632. list(qs), list(Book.objects.values_list("name", flat=True))
  633. )
  634. def test_annotation_disjunction(self):
  635. qs = Book.objects.annotate(n_authors=Count("authors")).filter(
  636. Q(n_authors=2) | Q(name="Python Web Development with Django")
  637. )
  638. self.assertQuerysetEqual(
  639. qs, [
  640. "Artificial Intelligence: A Modern Approach",
  641. "Python Web Development with Django",
  642. "The Definitive Guide to Django: Web Development Done Right",
  643. ],
  644. attrgetter("name")
  645. )
  646. qs = Book.objects.annotate(n_authors=Count("authors")).filter(
  647. Q(name="The Definitive Guide to Django: Web Development Done Right") | (Q(name="Artificial Intelligence: A Modern Approach") & Q(n_authors=3))
  648. )
  649. self.assertQuerysetEqual(
  650. qs, [
  651. "The Definitive Guide to Django: Web Development Done Right",
  652. ],
  653. attrgetter("name")
  654. )
  655. qs = Publisher.objects.annotate(
  656. rating_sum=Sum("book__rating"),
  657. book_count=Count("book")
  658. ).filter(
  659. Q(rating_sum__gt=5.5) | Q(rating_sum__isnull=True)
  660. ).order_by('pk')
  661. self.assertQuerysetEqual(
  662. qs, [
  663. "Apress",
  664. "Prentice Hall",
  665. "Jonno's House of Books",
  666. ],
  667. attrgetter("name")
  668. )
  669. qs = Publisher.objects.annotate(
  670. rating_sum=Sum("book__rating"),
  671. book_count=Count("book")
  672. ).filter(
  673. Q(pk__lt=F("book_count")) | Q(rating_sum=None)
  674. ).order_by("pk")
  675. self.assertQuerysetEqual(
  676. qs, [
  677. "Apress",
  678. "Jonno's House of Books",
  679. ],
  680. attrgetter("name")
  681. )
  682. def test_quoting_aggregate_order_by(self):
  683. qs = Book.objects.filter(
  684. name="Python Web Development with Django"
  685. ).annotate(
  686. authorCount=Count("authors")
  687. ).order_by("authorCount")
  688. self.assertQuerysetEqual(
  689. qs, [
  690. ("Python Web Development with Django", 3),
  691. ],
  692. lambda b: (b.name, b.authorCount)
  693. )
  694. @skipUnlessDBFeature('supports_stddev')
  695. def test_stddev(self):
  696. self.assertEqual(
  697. Book.objects.aggregate(StdDev('pages')),
  698. {'pages__stddev': Approximate(311.46, 1)}
  699. )
  700. self.assertEqual(
  701. Book.objects.aggregate(StdDev('rating')),
  702. {'rating__stddev': Approximate(0.60, 1)}
  703. )
  704. self.assertEqual(
  705. Book.objects.aggregate(StdDev('price')),
  706. {'price__stddev': Approximate(24.16, 2)}
  707. )
  708. self.assertEqual(
  709. Book.objects.aggregate(StdDev('pages', sample=True)),
  710. {'pages__stddev': Approximate(341.19, 2)}
  711. )
  712. self.assertEqual(
  713. Book.objects.aggregate(StdDev('rating', sample=True)),
  714. {'rating__stddev': Approximate(0.66, 2)}
  715. )
  716. self.assertEqual(
  717. Book.objects.aggregate(StdDev('price', sample=True)),
  718. {'price__stddev': Approximate(26.46, 1)}
  719. )
  720. self.assertEqual(
  721. Book.objects.aggregate(Variance('pages')),
  722. {'pages__variance': Approximate(97010.80, 1)}
  723. )
  724. self.assertEqual(
  725. Book.objects.aggregate(Variance('rating')),
  726. {'rating__variance': Approximate(0.36, 1)}
  727. )
  728. self.assertEqual(
  729. Book.objects.aggregate(Variance('price')),
  730. {'price__variance': Approximate(583.77, 1)}
  731. )
  732. self.assertEqual(
  733. Book.objects.aggregate(Variance('pages', sample=True)),
  734. {'pages__variance': Approximate(116412.96, 1)}
  735. )
  736. self.assertEqual(
  737. Book.objects.aggregate(Variance('rating', sample=True)),
  738. {'rating__variance': Approximate(0.44, 2)}
  739. )
  740. self.assertEqual(
  741. Book.objects.aggregate(Variance('price', sample=True)),
  742. {'price__variance': Approximate(700.53, 2)}
  743. )
  744. def test_filtering_by_annotation_name(self):
  745. # Regression test for #14476
  746. # The name of the explicitly provided annotation name in this case
  747. # poses no problem
  748. qs = Author.objects.annotate(book_cnt=Count('book')).filter(book_cnt=2).order_by('name')
  749. self.assertQuerysetEqual(
  750. qs,
  751. ['Peter Norvig'],
  752. lambda b: b.name
  753. )
  754. # Neither in this case
  755. qs = Author.objects.annotate(book_count=Count('book')).filter(book_count=2).order_by('name')
  756. self.assertQuerysetEqual(
  757. qs,
  758. ['Peter Norvig'],
  759. lambda b: b.name
  760. )
  761. # This case used to fail because the ORM couldn't resolve the
  762. # automatically generated annotation name `book__count`
  763. qs = Author.objects.annotate(Count('book')).filter(book__count=2).order_by('name')
  764. self.assertQuerysetEqual(
  765. qs,
  766. ['Peter Norvig'],
  767. lambda b: b.name
  768. )
  769. def test_type_conversion(self):
  770. # The database backend convert_values function should not try to covert
  771. # CharFields to float. Refs #13844.
  772. from django.db.models import CharField
  773. from django.db import connection
  774. testData = 'not_a_float_value'
  775. testField = CharField()
  776. self.assertEqual(
  777. connection.ops.convert_values(testData, testField),
  778. testData
  779. )
  780. def test_annotate_joins(self):
  781. """
  782. Test that the base table's join isn't promoted to LOUTER. This could
  783. cause the query generation to fail if there is an exclude() for fk-field
  784. in the query, too. Refs #19087.
  785. """
  786. qs = Book.objects.annotate(n=Count('pk'))
  787. self.assertIs(qs.query.alias_map['aggregation_regress_book'].join_type, None)
  788. # Check that the query executes without problems.
  789. self.assertEqual(len(qs.exclude(publisher=-1)), 6)
  790. @skipUnlessDBFeature("allows_group_by_pk")
  791. def test_aggregate_duplicate_columns(self):
  792. # Regression test for #17144
  793. results = Author.objects.annotate(num_contacts=Count('book_contact_set'))
  794. # There should only be one GROUP BY clause, for the `id` column.
  795. # `name` and `age` should not be grouped on.
  796. grouping, gb_params = results.query.get_compiler(using='default').get_grouping([], [])
  797. self.assertEqual(len(grouping), 1)
  798. assert 'id' in grouping[0]
  799. assert 'name' not in grouping[0]
  800. assert 'age' not in grouping[0]
  801. # The query group_by property should also only show the `id`.
  802. self.assertEqual(results.query.group_by, [('aggregation_regress_author', 'id')])
  803. # Ensure that we get correct results.
  804. self.assertEqual(
  805. [(a.name, a.num_contacts) for a in results.order_by('name')],
  806. [
  807. ('Adrian Holovaty', 1),
  808. ('Brad Dayley', 1),
  809. ('Jacob Kaplan-Moss', 0),
  810. ('James Bennett', 1),
  811. ('Jeffrey Forcier', 1),
  812. ('Paul Bissex', 0),
  813. ('Peter Norvig', 2),
  814. ('Stuart Russell', 0),
  815. ('Wesley J. Chun', 0),
  816. ]
  817. )
  818. @skipUnlessDBFeature("allows_group_by_pk")
  819. def test_aggregate_duplicate_columns_only(self):
  820. # Works with only() too.
  821. results = Author.objects.only('id', 'name').annotate(num_contacts=Count('book_contact_set'))
  822. grouping, gb_params = results.query.get_compiler(using='default').get_grouping([], [])
  823. self.assertEqual(len(grouping), 1)
  824. assert 'id' in grouping[0]
  825. assert 'name' not in grouping[0]
  826. assert 'age' not in grouping[0]
  827. # The query group_by property should also only show the `id`.
  828. self.assertEqual(results.query.group_by, [('aggregation_regress_author', 'id')])
  829. # Ensure that we get correct results.
  830. self.assertEqual(
  831. [(a.name, a.num_contacts) for a in results.order_by('name')],
  832. [
  833. ('Adrian Holovaty', 1),
  834. ('Brad Dayley', 1),
  835. ('Jacob Kaplan-Moss', 0),
  836. ('James Bennett', 1),
  837. ('Jeffrey Forcier', 1),
  838. ('Paul Bissex', 0),
  839. ('Peter Norvig', 2),
  840. ('Stuart Russell', 0),
  841. ('Wesley J. Chun', 0),
  842. ]
  843. )
  844. @skipUnlessDBFeature("allows_group_by_pk")
  845. def test_aggregate_duplicate_columns_select_related(self):
  846. # And select_related()
  847. results = Book.objects.select_related('contact').annotate(
  848. num_authors=Count('authors'))
  849. grouping, gb_params = results.query.get_compiler(using='default').get_grouping([], [])
  850. self.assertEqual(len(grouping), 1)
  851. assert 'id' in grouping[0]
  852. assert 'name' not in grouping[0]
  853. assert 'contact' not in grouping[0]
  854. # The query group_by property should also only show the `id`.
  855. self.assertEqual(results.query.group_by, [('aggregation_regress_book', 'id')])
  856. # Ensure that we get correct results.
  857. self.assertEqual(
  858. [(b.name, b.num_authors) for b in results.order_by('name')],
  859. [
  860. ('Artificial Intelligence: A Modern Approach', 2),
  861. ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1),
  862. ('Practical Django Projects', 1),
  863. ('Python Web Development with Django', 3),
  864. ('Sams Teach Yourself Django in 24 Hours', 1),
  865. ('The Definitive Guide to Django: Web Development Done Right', 2)
  866. ]
  867. )
  868. def test_reverse_join_trimming(self):
  869. qs = Author.objects.annotate(Count('book_contact_set__contact'))
  870. self.assertIn(' JOIN ', str(qs.query))
  871. def test_aggregation_with_generic_reverse_relation(self):
  872. """
  873. Regression test for #10870: Aggregates with joins ignore extra
  874. filters provided by setup_joins
  875. tests aggregations with generic reverse relations
  876. """
  877. b = Book.objects.get(name='Practical Django Projects')
  878. ItemTag.objects.create(object_id=b.id, tag='intermediate',
  879. content_type=ContentType.objects.get_for_model(b))
  880. ItemTag.objects.create(object_id=b.id, tag='django',
  881. content_type=ContentType.objects.get_for_model(b))
  882. # Assign a tag to model with same PK as the book above. If the JOIN
  883. # used in aggregation doesn't have content type as part of the
  884. # condition the annotation will also count the 'hi mom' tag for b.
  885. wmpk = WithManualPK.objects.create(id=b.pk)
  886. ItemTag.objects.create(object_id=wmpk.id, tag='hi mom',
  887. content_type=ContentType.objects.get_for_model(wmpk))
  888. b = Book.objects.get(name__startswith='Paradigms of Artificial Intelligence')
  889. ItemTag.objects.create(object_id=b.id, tag='intermediate',
  890. content_type=ContentType.objects.get_for_model(b))
  891. self.assertEqual(Book.objects.aggregate(Count('tags')), {'tags__count': 3})
  892. results = Book.objects.annotate(Count('tags')).order_by('-tags__count', 'name')
  893. self.assertEqual(
  894. [(b.name, b.tags__count) for b in results],
  895. [
  896. ('Practical Django Projects', 2),
  897. ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1),
  898. ('Artificial Intelligence: A Modern Approach', 0),
  899. ('Python Web Development with Django', 0),
  900. ('Sams Teach Yourself Django in 24 Hours', 0),
  901. ('The Definitive Guide to Django: Web Development Done Right', 0)
  902. ]
  903. )
  904. def test_negated_aggregation(self):
  905. expected_results = Author.objects.exclude(
  906. pk__in=Author.objects.annotate(book_cnt=Count('book')).filter(book_cnt=2)
  907. ).order_by('name')
  908. expected_results = [a.name for a in expected_results]
  909. qs = Author.objects.annotate(book_cnt=Count('book')).exclude(
  910. Q(book_cnt=2), Q(book_cnt=2)).order_by('name')
  911. self.assertQuerysetEqual(
  912. qs,
  913. expected_results,
  914. lambda b: b.name
  915. )
  916. expected_results = Author.objects.exclude(
  917. pk__in=Author.objects.annotate(book_cnt=Count('book')).filter(book_cnt=2)
  918. ).order_by('name')
  919. expected_results = [a.name for a in expected_results]
  920. qs = Author.objects.annotate(book_cnt=Count('book')).exclude(Q(book_cnt=2)|Q(book_cnt=2)).order_by('name')
  921. self.assertQuerysetEqual(
  922. qs,
  923. expected_results,
  924. lambda b: b.name
  925. )
  926. def test_name_filters(self):
  927. qs = Author.objects.annotate(Count('book')).filter(
  928. Q(book__count__exact=2)|Q(name='Adrian Holovaty')
  929. ).order_by('name')
  930. self.assertQuerysetEqual(
  931. qs,
  932. ['Adrian Holovaty', 'Peter Norvig'],
  933. lambda b: b.name
  934. )
  935. def test_name_expressions(self):
  936. # Test that aggregates are spotted corretly from F objects.
  937. # Note that Adrian's age is 34 in the fixtures, and he has one book
  938. # so both conditions match one author.
  939. qs = Author.objects.annotate(Count('book')).filter(
  940. Q(name='Peter Norvig')|Q(age=F('book__count') + 33)
  941. ).order_by('name')
  942. self.assertQuerysetEqual(
  943. qs,
  944. ['Adrian Holovaty', 'Peter Norvig'],
  945. lambda b: b.name
  946. )
  947. def test_ticket_11293(self):
  948. q1 = Q(price__gt=50)
  949. q2 = Q(authors__count__gt=1)
  950. query = Book.objects.annotate(Count('authors')).filter(
  951. q1 | q2).order_by('pk')
  952. self.assertQuerysetEqual(
  953. query, [1, 4, 5, 6],
  954. lambda b: b.pk)
  955. def test_ticket_11293_q_immutable(self):
  956. """
  957. Check that splitting a q object to parts for where/having doesn't alter
  958. the original q-object.
  959. """
  960. q1 = Q(isbn='')
  961. q2 = Q(authors__count__gt=1)
  962. query = Book.objects.annotate(Count('authors'))
  963. query.filter(q1 | q2)
  964. self.assertEqual(len(q2.children), 1)
  965. def test_fobj_group_by(self):
  966. """
  967. Check that an F() object referring to related column works correctly
  968. in group by.
  969. """
  970. qs = Book.objects.annotate(
  971. acount=Count('authors')
  972. ).filter(
  973. acount=F('publisher__num_awards')
  974. )
  975. self.assertQuerysetEqual(
  976. qs, ['Sams Teach Yourself Django in 24 Hours'],
  977. lambda b: b.name)