tests.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. from __future__ import unicode_literals
  2. import datetime
  3. import re
  4. from decimal import Decimal
  5. from django.core.exceptions import FieldError
  6. from django.db import connection
  7. from django.db.models import (
  8. F, Avg, Count, DecimalField, DurationField, FloatField, Func, IntegerField,
  9. Max, Min, Sum, Value,
  10. )
  11. from django.test import TestCase
  12. from django.test.utils import Approximate, CaptureQueriesContext
  13. from django.utils import six, timezone
  14. from .models import Author, Book, Publisher, Store
  15. class AggregateTestCase(TestCase):
  16. @classmethod
  17. def setUpTestData(cls):
  18. cls.a1 = Author.objects.create(name='Adrian Holovaty', age=34)
  19. cls.a2 = Author.objects.create(name='Jacob Kaplan-Moss', age=35)
  20. cls.a3 = Author.objects.create(name='Brad Dayley', age=45)
  21. cls.a4 = Author.objects.create(name='James Bennett', age=29)
  22. cls.a5 = Author.objects.create(name='Jeffrey Forcier', age=37)
  23. cls.a6 = Author.objects.create(name='Paul Bissex', age=29)
  24. cls.a7 = Author.objects.create(name='Wesley J. Chun', age=25)
  25. cls.a8 = Author.objects.create(name='Peter Norvig', age=57)
  26. cls.a9 = Author.objects.create(name='Stuart Russell', age=46)
  27. cls.a1.friends.add(cls.a2, cls.a4)
  28. cls.a2.friends.add(cls.a1, cls.a7)
  29. cls.a4.friends.add(cls.a1)
  30. cls.a5.friends.add(cls.a6, cls.a7)
  31. cls.a6.friends.add(cls.a5, cls.a7)
  32. cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
  33. cls.a8.friends.add(cls.a9)
  34. cls.a9.friends.add(cls.a8)
  35. cls.p1 = Publisher.objects.create(name='Apress', num_awards=3, duration=datetime.timedelta(days=1))
  36. cls.p2 = Publisher.objects.create(name='Sams', num_awards=1, duration=datetime.timedelta(days=2))
  37. cls.p3 = Publisher.objects.create(name='Prentice Hall', num_awards=7)
  38. cls.p4 = Publisher.objects.create(name='Morgan Kaufmann', num_awards=9)
  39. cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
  40. cls.b1 = Book.objects.create(
  41. isbn='159059725', name='The Definitive Guide to Django: Web Development Done Right',
  42. pages=447, rating=4.5, price=Decimal('30.00'), contact=cls.a1, publisher=cls.p1,
  43. pubdate=datetime.date(2007, 12, 6)
  44. )
  45. cls.b2 = Book.objects.create(
  46. isbn='067232959', name='Sams Teach Yourself Django in 24 Hours',
  47. pages=528, rating=3.0, price=Decimal('23.09'), contact=cls.a3, publisher=cls.p2,
  48. pubdate=datetime.date(2008, 3, 3)
  49. )
  50. cls.b3 = Book.objects.create(
  51. isbn='159059996', name='Practical Django Projects',
  52. pages=300, rating=4.0, price=Decimal('29.69'), contact=cls.a4, publisher=cls.p1,
  53. pubdate=datetime.date(2008, 6, 23)
  54. )
  55. cls.b4 = Book.objects.create(
  56. isbn='013235613', name='Python Web Development with Django',
  57. pages=350, rating=4.0, price=Decimal('29.69'), contact=cls.a5, publisher=cls.p3,
  58. pubdate=datetime.date(2008, 11, 3)
  59. )
  60. cls.b5 = Book.objects.create(
  61. isbn='013790395', name='Artificial Intelligence: A Modern Approach',
  62. pages=1132, rating=4.0, price=Decimal('82.80'), contact=cls.a8, publisher=cls.p3,
  63. pubdate=datetime.date(1995, 1, 15)
  64. )
  65. cls.b6 = Book.objects.create(
  66. isbn='155860191', name='Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp',
  67. pages=946, rating=5.0, price=Decimal('75.00'), contact=cls.a8, publisher=cls.p4,
  68. pubdate=datetime.date(1991, 10, 15)
  69. )
  70. cls.b1.authors.add(cls.a1, cls.a2)
  71. cls.b2.authors.add(cls.a3)
  72. cls.b3.authors.add(cls.a4)
  73. cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
  74. cls.b5.authors.add(cls.a8, cls.a9)
  75. cls.b6.authors.add(cls.a8)
  76. s1 = Store.objects.create(
  77. name='Amazon.com',
  78. original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
  79. friday_night_closing=datetime.time(23, 59, 59)
  80. )
  81. s2 = Store.objects.create(
  82. name='Books.com',
  83. original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
  84. friday_night_closing=datetime.time(23, 59, 59)
  85. )
  86. s3 = Store.objects.create(
  87. name="Mamma and Pappa's Books",
  88. original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
  89. friday_night_closing=datetime.time(21, 30)
  90. )
  91. s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
  92. s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
  93. s3.books.add(cls.b3, cls.b4, cls.b6)
  94. def test_empty_aggregate(self):
  95. self.assertEqual(Author.objects.all().aggregate(), {})
  96. def test_aggregate_in_order_by(self):
  97. msg = (
  98. 'Using an aggregate in order_by() without also including it in '
  99. 'annotate() is not allowed: Avg(F(book__rating)'
  100. )
  101. with self.assertRaisesMessage(FieldError, msg):
  102. Author.objects.values('age').order_by(Avg('book__rating'))
  103. def test_single_aggregate(self):
  104. vals = Author.objects.aggregate(Avg("age"))
  105. self.assertEqual(vals, {"age__avg": Approximate(37.4, places=1)})
  106. def test_multiple_aggregates(self):
  107. vals = Author.objects.aggregate(Sum("age"), Avg("age"))
  108. self.assertEqual(vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)})
  109. def test_filter_aggregate(self):
  110. vals = Author.objects.filter(age__gt=29).aggregate(Sum("age"))
  111. self.assertEqual(len(vals), 1)
  112. self.assertEqual(vals["age__sum"], 254)
  113. def test_related_aggregate(self):
  114. vals = Author.objects.aggregate(Avg("friends__age"))
  115. self.assertEqual(len(vals), 1)
  116. self.assertAlmostEqual(vals["friends__age__avg"], 34.07, places=2)
  117. vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age"))
  118. self.assertEqual(len(vals), 1)
  119. self.assertAlmostEqual(vals["authors__age__avg"], 38.2857, places=2)
  120. vals = Author.objects.all().filter(name__contains="a").aggregate(Avg("book__rating"))
  121. self.assertEqual(len(vals), 1)
  122. self.assertEqual(vals["book__rating__avg"], 4.0)
  123. vals = Book.objects.aggregate(Sum("publisher__num_awards"))
  124. self.assertEqual(len(vals), 1)
  125. self.assertEqual(vals["publisher__num_awards__sum"], 30)
  126. vals = Publisher.objects.aggregate(Sum("book__price"))
  127. self.assertEqual(len(vals), 1)
  128. self.assertEqual(vals["book__price__sum"], Decimal("270.27"))
  129. def test_aggregate_multi_join(self):
  130. vals = Store.objects.aggregate(Max("books__authors__age"))
  131. self.assertEqual(len(vals), 1)
  132. self.assertEqual(vals["books__authors__age__max"], 57)
  133. vals = Author.objects.aggregate(Min("book__publisher__num_awards"))
  134. self.assertEqual(len(vals), 1)
  135. self.assertEqual(vals["book__publisher__num_awards__min"], 1)
  136. def test_aggregate_alias(self):
  137. vals = Store.objects.filter(name="Amazon.com").aggregate(amazon_mean=Avg("books__rating"))
  138. self.assertEqual(len(vals), 1)
  139. self.assertAlmostEqual(vals["amazon_mean"], 4.08, places=2)
  140. def test_annotate_basic(self):
  141. self.assertQuerysetEqual(
  142. Book.objects.annotate().order_by('pk'), [
  143. "The Definitive Guide to Django: Web Development Done Right",
  144. "Sams Teach Yourself Django in 24 Hours",
  145. "Practical Django Projects",
  146. "Python Web Development with Django",
  147. "Artificial Intelligence: A Modern Approach",
  148. "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp"
  149. ],
  150. lambda b: b.name
  151. )
  152. books = Book.objects.annotate(mean_age=Avg("authors__age"))
  153. b = books.get(pk=self.b1.pk)
  154. self.assertEqual(
  155. b.name,
  156. 'The Definitive Guide to Django: Web Development Done Right'
  157. )
  158. self.assertEqual(b.mean_age, 34.5)
  159. def test_annotate_defer(self):
  160. qs = Book.objects.annotate(
  161. page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)
  162. rows = [
  163. (1, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right")
  164. ]
  165. self.assertQuerysetEqual(
  166. qs.order_by('pk'), rows,
  167. lambda r: (r.id, r.isbn, r.page_sum, r.name)
  168. )
  169. def test_annotate_defer_select_related(self):
  170. qs = Book.objects.select_related('contact').annotate(
  171. page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)
  172. rows = [
  173. (1, "159059725", 447, "Adrian Holovaty",
  174. "The Definitive Guide to Django: Web Development Done Right")
  175. ]
  176. self.assertQuerysetEqual(
  177. qs.order_by('pk'), rows,
  178. lambda r: (r.id, r.isbn, r.page_sum, r.contact.name, r.name)
  179. )
  180. def test_annotate_m2m(self):
  181. books = Book.objects.filter(rating__lt=4.5).annotate(Avg("authors__age")).order_by("name")
  182. self.assertQuerysetEqual(
  183. books, [
  184. ('Artificial Intelligence: A Modern Approach', 51.5),
  185. ('Practical Django Projects', 29.0),
  186. ('Python Web Development with Django', Approximate(30.3, places=1)),
  187. ('Sams Teach Yourself Django in 24 Hours', 45.0)
  188. ],
  189. lambda b: (b.name, b.authors__age__avg),
  190. )
  191. books = Book.objects.annotate(num_authors=Count("authors")).order_by("name")
  192. self.assertQuerysetEqual(
  193. books, [
  194. ('Artificial Intelligence: A Modern Approach', 2),
  195. ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1),
  196. ('Practical Django Projects', 1),
  197. ('Python Web Development with Django', 3),
  198. ('Sams Teach Yourself Django in 24 Hours', 1),
  199. ('The Definitive Guide to Django: Web Development Done Right', 2)
  200. ],
  201. lambda b: (b.name, b.num_authors)
  202. )
  203. def test_backwards_m2m_annotate(self):
  204. authors = Author.objects.filter(name__contains="a").annotate(Avg("book__rating")).order_by("name")
  205. self.assertQuerysetEqual(
  206. authors, [
  207. ('Adrian Holovaty', 4.5),
  208. ('Brad Dayley', 3.0),
  209. ('Jacob Kaplan-Moss', 4.5),
  210. ('James Bennett', 4.0),
  211. ('Paul Bissex', 4.0),
  212. ('Stuart Russell', 4.0)
  213. ],
  214. lambda a: (a.name, a.book__rating__avg)
  215. )
  216. authors = Author.objects.annotate(num_books=Count("book")).order_by("name")
  217. self.assertQuerysetEqual(
  218. authors, [
  219. ('Adrian Holovaty', 1),
  220. ('Brad Dayley', 1),
  221. ('Jacob Kaplan-Moss', 1),
  222. ('James Bennett', 1),
  223. ('Jeffrey Forcier', 1),
  224. ('Paul Bissex', 1),
  225. ('Peter Norvig', 2),
  226. ('Stuart Russell', 1),
  227. ('Wesley J. Chun', 1)
  228. ],
  229. lambda a: (a.name, a.num_books)
  230. )
  231. def test_reverse_fkey_annotate(self):
  232. books = Book.objects.annotate(Sum("publisher__num_awards")).order_by("name")
  233. self.assertQuerysetEqual(
  234. books, [
  235. ('Artificial Intelligence: A Modern Approach', 7),
  236. ('Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 9),
  237. ('Practical Django Projects', 3),
  238. ('Python Web Development with Django', 7),
  239. ('Sams Teach Yourself Django in 24 Hours', 1),
  240. ('The Definitive Guide to Django: Web Development Done Right', 3)
  241. ],
  242. lambda b: (b.name, b.publisher__num_awards__sum)
  243. )
  244. publishers = Publisher.objects.annotate(Sum("book__price")).order_by("name")
  245. self.assertQuerysetEqual(
  246. publishers, [
  247. ('Apress', Decimal("59.69")),
  248. ("Jonno's House of Books", None),
  249. ('Morgan Kaufmann', Decimal("75.00")),
  250. ('Prentice Hall', Decimal("112.49")),
  251. ('Sams', Decimal("23.09"))
  252. ],
  253. lambda p: (p.name, p.book__price__sum)
  254. )
  255. def test_annotate_values(self):
  256. books = list(Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values())
  257. self.assertEqual(
  258. books, [
  259. {
  260. "contact_id": 1,
  261. "id": 1,
  262. "isbn": "159059725",
  263. "mean_age": 34.5,
  264. "name": "The Definitive Guide to Django: Web Development Done Right",
  265. "pages": 447,
  266. "price": Approximate(Decimal("30")),
  267. "pubdate": datetime.date(2007, 12, 6),
  268. "publisher_id": 1,
  269. "rating": 4.5,
  270. }
  271. ]
  272. )
  273. books = (
  274. Book.objects
  275. .filter(pk=self.b1.pk)
  276. .annotate(mean_age=Avg('authors__age'))
  277. .values('pk', 'isbn', 'mean_age')
  278. )
  279. self.assertEqual(
  280. list(books), [
  281. {
  282. "pk": 1,
  283. "isbn": "159059725",
  284. "mean_age": 34.5,
  285. }
  286. ]
  287. )
  288. books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values("name")
  289. self.assertEqual(
  290. list(books), [
  291. {
  292. "name": "The Definitive Guide to Django: Web Development Done Right"
  293. }
  294. ]
  295. )
  296. books = Book.objects.filter(pk=self.b1.pk).values().annotate(mean_age=Avg('authors__age'))
  297. self.assertEqual(
  298. list(books), [
  299. {
  300. "contact_id": 1,
  301. "id": 1,
  302. "isbn": "159059725",
  303. "mean_age": 34.5,
  304. "name": "The Definitive Guide to Django: Web Development Done Right",
  305. "pages": 447,
  306. "price": Approximate(Decimal("30")),
  307. "pubdate": datetime.date(2007, 12, 6),
  308. "publisher_id": 1,
  309. "rating": 4.5,
  310. }
  311. ]
  312. )
  313. books = (
  314. Book.objects
  315. .values("rating")
  316. .annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age"))
  317. .order_by("rating")
  318. )
  319. self.assertEqual(
  320. list(books), [
  321. {
  322. "rating": 3.0,
  323. "n_authors": 1,
  324. "mean_age": 45.0,
  325. },
  326. {
  327. "rating": 4.0,
  328. "n_authors": 6,
  329. "mean_age": Approximate(37.16, places=1)
  330. },
  331. {
  332. "rating": 4.5,
  333. "n_authors": 2,
  334. "mean_age": 34.5,
  335. },
  336. {
  337. "rating": 5.0,
  338. "n_authors": 1,
  339. "mean_age": 57.0,
  340. }
  341. ]
  342. )
  343. authors = Author.objects.annotate(Avg("friends__age")).order_by("name")
  344. self.assertEqual(len(authors), 9)
  345. self.assertQuerysetEqual(
  346. authors, [
  347. ('Adrian Holovaty', 32.0),
  348. ('Brad Dayley', None),
  349. ('Jacob Kaplan-Moss', 29.5),
  350. ('James Bennett', 34.0),
  351. ('Jeffrey Forcier', 27.0),
  352. ('Paul Bissex', 31.0),
  353. ('Peter Norvig', 46.0),
  354. ('Stuart Russell', 57.0),
  355. ('Wesley J. Chun', Approximate(33.66, places=1))
  356. ],
  357. lambda a: (a.name, a.friends__age__avg)
  358. )
  359. def test_count(self):
  360. vals = Book.objects.aggregate(Count("rating"))
  361. self.assertEqual(vals, {"rating__count": 6})
  362. vals = Book.objects.aggregate(Count("rating", distinct=True))
  363. self.assertEqual(vals, {"rating__count": 4})
  364. def test_count_star(self):
  365. with self.assertNumQueries(1) as ctx:
  366. Book.objects.aggregate(n=Count("*"))
  367. sql = ctx.captured_queries[0]['sql']
  368. self.assertIn('SELECT COUNT(*) ', sql)
  369. def test_non_grouped_annotation_not_in_group_by(self):
  370. """
  371. An annotation not included in values() before an aggregate should be
  372. excluded from the group by clause.
  373. """
  374. qs = (
  375. Book.objects.annotate(xprice=F('price')).filter(rating=4.0).values('rating')
  376. .annotate(count=Count('publisher_id', distinct=True)).values('count', 'rating').order_by('count')
  377. )
  378. self.assertEqual(
  379. list(qs), [
  380. {'rating': 4.0, 'count': 2},
  381. ]
  382. )
  383. def test_grouped_annotation_in_group_by(self):
  384. """
  385. An annotation included in values() before an aggregate should be
  386. included in the group by clause.
  387. """
  388. qs = (
  389. Book.objects.annotate(xprice=F('price')).filter(rating=4.0).values('rating', 'xprice')
  390. .annotate(count=Count('publisher_id', distinct=True)).values('count', 'rating').order_by('count')
  391. )
  392. self.assertEqual(
  393. list(qs), [
  394. {'rating': 4.0, 'count': 1},
  395. {'rating': 4.0, 'count': 2},
  396. ]
  397. )
  398. def test_fkey_aggregate(self):
  399. explicit = list(Author.objects.annotate(Count('book__id')))
  400. implicit = list(Author.objects.annotate(Count('book')))
  401. self.assertEqual(explicit, implicit)
  402. def test_annotate_ordering(self):
  403. books = Book.objects.values('rating').annotate(oldest=Max('authors__age')).order_by('oldest', 'rating')
  404. self.assertEqual(
  405. list(books), [
  406. {
  407. "rating": 4.5,
  408. "oldest": 35,
  409. },
  410. {
  411. "rating": 3.0,
  412. "oldest": 45
  413. },
  414. {
  415. "rating": 4.0,
  416. "oldest": 57,
  417. },
  418. {
  419. "rating": 5.0,
  420. "oldest": 57,
  421. }
  422. ]
  423. )
  424. books = Book.objects.values("rating").annotate(oldest=Max("authors__age")).order_by("-oldest", "-rating")
  425. self.assertEqual(
  426. list(books), [
  427. {
  428. "rating": 5.0,
  429. "oldest": 57,
  430. },
  431. {
  432. "rating": 4.0,
  433. "oldest": 57,
  434. },
  435. {
  436. "rating": 3.0,
  437. "oldest": 45,
  438. },
  439. {
  440. "rating": 4.5,
  441. "oldest": 35,
  442. }
  443. ]
  444. )
  445. def test_aggregate_annotation(self):
  446. vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(Avg("num_authors"))
  447. self.assertEqual(vals, {"num_authors__avg": Approximate(1.66, places=1)})
  448. def test_avg_duration_field(self):
  449. self.assertEqual(
  450. Publisher.objects.aggregate(Avg('duration', output_field=DurationField())),
  451. {'duration__avg': datetime.timedelta(days=1, hours=12)}
  452. )
  453. def test_sum_duration_field(self):
  454. self.assertEqual(
  455. Publisher.objects.aggregate(Sum('duration', output_field=DurationField())),
  456. {'duration__sum': datetime.timedelta(days=3)}
  457. )
  458. def test_sum_distinct_aggregate(self):
  459. """
  460. Sum on a distinct() QuerySet should aggregate only the distinct items.
  461. """
  462. authors = Author.objects.filter(book__in=[5, 6])
  463. self.assertEqual(authors.count(), 3)
  464. distinct_authors = authors.distinct()
  465. self.assertEqual(distinct_authors.count(), 2)
  466. # Selected author ages are 57 and 46
  467. age_sum = distinct_authors.aggregate(Sum('age'))
  468. self.assertEqual(age_sum['age__sum'], 103)
  469. def test_filtering(self):
  470. p = Publisher.objects.create(name='Expensive Publisher', num_awards=0)
  471. Book.objects.create(
  472. name='ExpensiveBook1',
  473. pages=1,
  474. isbn='111',
  475. rating=3.5,
  476. price=Decimal("1000"),
  477. publisher=p,
  478. contact_id=1,
  479. pubdate=datetime.date(2008, 12, 1)
  480. )
  481. Book.objects.create(
  482. name='ExpensiveBook2',
  483. pages=1,
  484. isbn='222',
  485. rating=4.0,
  486. price=Decimal("1000"),
  487. publisher=p,
  488. contact_id=1,
  489. pubdate=datetime.date(2008, 12, 2)
  490. )
  491. Book.objects.create(
  492. name='ExpensiveBook3',
  493. pages=1,
  494. isbn='333',
  495. rating=4.5,
  496. price=Decimal("35"),
  497. publisher=p,
  498. contact_id=1,
  499. pubdate=datetime.date(2008, 12, 3)
  500. )
  501. publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk")
  502. self.assertQuerysetEqual(
  503. publishers, [
  504. "Apress",
  505. "Prentice Hall",
  506. "Expensive Publisher",
  507. ],
  508. lambda p: p.name,
  509. )
  510. publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).order_by("pk")
  511. self.assertQuerysetEqual(
  512. publishers, [
  513. "Apress",
  514. "Apress",
  515. "Sams",
  516. "Prentice Hall",
  517. "Expensive Publisher",
  518. ],
  519. lambda p: p.name
  520. )
  521. publishers = (
  522. Publisher.objects
  523. .annotate(num_books=Count("book__id"))
  524. .filter(num_books__gt=1, book__price__lt=Decimal("40.0"))
  525. .order_by("pk")
  526. )
  527. self.assertQuerysetEqual(
  528. publishers, [
  529. "Apress",
  530. "Prentice Hall",
  531. "Expensive Publisher",
  532. ],
  533. lambda p: p.name,
  534. )
  535. publishers = (
  536. Publisher.objects
  537. .filter(book__price__lt=Decimal("40.0"))
  538. .annotate(num_books=Count("book__id"))
  539. .filter(num_books__gt=1)
  540. .order_by("pk")
  541. )
  542. self.assertQuerysetEqual(
  543. publishers, [
  544. "Apress",
  545. ],
  546. lambda p: p.name
  547. )
  548. publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__range=[1, 3]).order_by("pk")
  549. self.assertQuerysetEqual(
  550. publishers, [
  551. "Apress",
  552. "Sams",
  553. "Prentice Hall",
  554. "Morgan Kaufmann",
  555. "Expensive Publisher",
  556. ],
  557. lambda p: p.name
  558. )
  559. publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__range=[1, 2]).order_by("pk")
  560. self.assertQuerysetEqual(
  561. publishers, [
  562. "Apress",
  563. "Sams",
  564. "Prentice Hall",
  565. "Morgan Kaufmann",
  566. ],
  567. lambda p: p.name
  568. )
  569. publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__in=[1, 3]).order_by("pk")
  570. self.assertQuerysetEqual(
  571. publishers, [
  572. "Sams",
  573. "Morgan Kaufmann",
  574. "Expensive Publisher",
  575. ],
  576. lambda p: p.name,
  577. )
  578. publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__isnull=True)
  579. self.assertEqual(len(publishers), 0)
  580. def test_annotation(self):
  581. vals = Author.objects.filter(pk=self.a1.pk).aggregate(Count("friends__id"))
  582. self.assertEqual(vals, {"friends__id__count": 2})
  583. books = Book.objects.annotate(num_authors=Count("authors__name")).filter(num_authors__exact=2).order_by("pk")
  584. self.assertQuerysetEqual(
  585. books, [
  586. "The Definitive Guide to Django: Web Development Done Right",
  587. "Artificial Intelligence: A Modern Approach",
  588. ],
  589. lambda b: b.name
  590. )
  591. authors = (
  592. Author.objects
  593. .annotate(num_friends=Count("friends__id", distinct=True))
  594. .filter(num_friends=0)
  595. .order_by("pk")
  596. )
  597. self.assertQuerysetEqual(
  598. authors, [
  599. "Brad Dayley",
  600. ],
  601. lambda a: a.name
  602. )
  603. publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk")
  604. self.assertQuerysetEqual(
  605. publishers, [
  606. "Apress",
  607. "Prentice Hall",
  608. ],
  609. lambda p: p.name
  610. )
  611. publishers = (
  612. Publisher.objects
  613. .filter(book__price__lt=Decimal("40.0"))
  614. .annotate(num_books=Count("book__id"))
  615. .filter(num_books__gt=1)
  616. )
  617. self.assertQuerysetEqual(
  618. publishers, [
  619. "Apress",
  620. ],
  621. lambda p: p.name
  622. )
  623. books = (
  624. Book.objects
  625. .annotate(num_authors=Count("authors__id"))
  626. .filter(authors__name__contains="Norvig", num_authors__gt=1)
  627. )
  628. self.assertQuerysetEqual(
  629. books, [
  630. "Artificial Intelligence: A Modern Approach",
  631. ],
  632. lambda b: b.name
  633. )
  634. def test_more_aggregation(self):
  635. a = Author.objects.get(name__contains='Norvig')
  636. b = Book.objects.get(name__contains='Done Right')
  637. b.authors.add(a)
  638. b.save()
  639. vals = (
  640. Book.objects
  641. .annotate(num_authors=Count("authors__id"))
  642. .filter(authors__name__contains="Norvig", num_authors__gt=1)
  643. .aggregate(Avg("rating"))
  644. )
  645. self.assertEqual(vals, {"rating__avg": 4.25})
  646. def test_even_more_aggregate(self):
  647. publishers = Publisher.objects.annotate(
  648. earliest_book=Min("book__pubdate"),
  649. ).exclude(earliest_book=None).order_by("earliest_book").values(
  650. 'earliest_book',
  651. 'num_awards',
  652. 'id',
  653. 'name',
  654. )
  655. self.assertEqual(
  656. list(publishers), [
  657. {
  658. 'earliest_book': datetime.date(1991, 10, 15),
  659. 'num_awards': 9,
  660. 'id': 4,
  661. 'name': 'Morgan Kaufmann'
  662. },
  663. {
  664. 'earliest_book': datetime.date(1995, 1, 15),
  665. 'num_awards': 7,
  666. 'id': 3,
  667. 'name': 'Prentice Hall'
  668. },
  669. {
  670. 'earliest_book': datetime.date(2007, 12, 6),
  671. 'num_awards': 3,
  672. 'id': 1,
  673. 'name': 'Apress'
  674. },
  675. {
  676. 'earliest_book': datetime.date(2008, 3, 3),
  677. 'num_awards': 1,
  678. 'id': 2,
  679. 'name': 'Sams'
  680. }
  681. ]
  682. )
  683. vals = Store.objects.aggregate(Max("friday_night_closing"), Min("original_opening"))
  684. self.assertEqual(
  685. vals,
  686. {
  687. "friday_night_closing__max": datetime.time(23, 59, 59),
  688. "original_opening__min": datetime.datetime(1945, 4, 25, 16, 24, 14),
  689. }
  690. )
  691. def test_annotate_values_list(self):
  692. books = (
  693. Book.objects
  694. .filter(pk=self.b1.pk)
  695. .annotate(mean_age=Avg("authors__age"))
  696. .values_list("pk", "isbn", "mean_age")
  697. )
  698. self.assertEqual(
  699. list(books), [
  700. (1, "159059725", 34.5),
  701. ]
  702. )
  703. books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("isbn")
  704. self.assertEqual(
  705. list(books), [
  706. ('159059725',)
  707. ]
  708. )
  709. books = Book.objects.filter(pk=self.b1.pk).annotate(mean_age=Avg("authors__age")).values_list("mean_age")
  710. self.assertEqual(
  711. list(books), [
  712. (34.5,)
  713. ]
  714. )
  715. books = (
  716. Book.objects
  717. .filter(pk=self.b1.pk)
  718. .annotate(mean_age=Avg("authors__age"))
  719. .values_list("mean_age", flat=True)
  720. )
  721. self.assertEqual(list(books), [34.5])
  722. books = Book.objects.values_list("price").annotate(count=Count("price")).order_by("-count", "price")
  723. self.assertEqual(
  724. list(books), [
  725. (Decimal("29.69"), 2),
  726. (Decimal('23.09'), 1),
  727. (Decimal('30'), 1),
  728. (Decimal('75'), 1),
  729. (Decimal('82.8'), 1),
  730. ]
  731. )
  732. def test_dates_with_aggregation(self):
  733. """
  734. Test that .dates() returns a distinct set of dates when applied to a
  735. QuerySet with aggregation.
  736. Refs #18056. Previously, .dates() would return distinct (date_kind,
  737. aggregation) sets, in this case (year, num_authors), so 2008 would be
  738. returned twice because there are books from 2008 with a different
  739. number of authors.
  740. """
  741. dates = Book.objects.annotate(num_authors=Count("authors")).dates('pubdate', 'year')
  742. self.assertQuerysetEqual(
  743. dates, [
  744. "datetime.date(1991, 1, 1)",
  745. "datetime.date(1995, 1, 1)",
  746. "datetime.date(2007, 1, 1)",
  747. "datetime.date(2008, 1, 1)"
  748. ]
  749. )
  750. def test_values_aggregation(self):
  751. # Refs #20782
  752. max_rating = Book.objects.values('rating').aggregate(max_rating=Max('rating'))
  753. self.assertEqual(max_rating['max_rating'], 5)
  754. max_books_per_rating = Book.objects.values('rating').annotate(
  755. books_per_rating=Count('id')
  756. ).aggregate(Max('books_per_rating'))
  757. self.assertEqual(
  758. max_books_per_rating,
  759. {'books_per_rating__max': 3})
  760. def test_ticket17424(self):
  761. """
  762. Check that doing exclude() on a foreign model after annotate()
  763. doesn't crash.
  764. """
  765. all_books = list(Book.objects.values_list('pk', flat=True).order_by('pk'))
  766. annotated_books = Book.objects.order_by('pk').annotate(one=Count("id"))
  767. # The value doesn't matter, we just need any negative
  768. # constraint on a related model that's a noop.
  769. excluded_books = annotated_books.exclude(publisher__name="__UNLIKELY_VALUE__")
  770. # Try to generate query tree
  771. str(excluded_books.query)
  772. self.assertQuerysetEqual(excluded_books, all_books, lambda x: x.pk)
  773. # Check internal state
  774. self.assertIsNone(annotated_books.query.alias_map["aggregation_book"].join_type)
  775. self.assertIsNone(excluded_books.query.alias_map["aggregation_book"].join_type)
  776. def test_ticket12886(self):
  777. """
  778. Check that aggregation over sliced queryset works correctly.
  779. """
  780. qs = Book.objects.all().order_by('-rating')[0:3]
  781. vals = qs.aggregate(average_top3_rating=Avg('rating'))['average_top3_rating']
  782. self.assertAlmostEqual(vals, 4.5, places=2)
  783. def test_ticket11881(self):
  784. """
  785. Check that subqueries do not needlessly contain ORDER BY, SELECT FOR UPDATE
  786. or select_related() stuff.
  787. """
  788. qs = Book.objects.all().select_for_update().order_by(
  789. 'pk').select_related('publisher').annotate(max_pk=Max('pk'))
  790. with CaptureQueriesContext(connection) as captured_queries:
  791. qs.aggregate(avg_pk=Avg('max_pk'))
  792. self.assertEqual(len(captured_queries), 1)
  793. qstr = captured_queries[0]['sql'].lower()
  794. self.assertNotIn('for update', qstr)
  795. forced_ordering = connection.ops.force_no_ordering()
  796. if forced_ordering:
  797. # If the backend needs to force an ordering we make sure it's
  798. # the only "ORDER BY" clause present in the query.
  799. self.assertEqual(
  800. re.findall(r'order by (\w+)', qstr),
  801. [', '.join(f[1][0] for f in forced_ordering).lower()]
  802. )
  803. else:
  804. self.assertNotIn('order by', qstr)
  805. self.assertEqual(qstr.count(' join '), 0)
  806. def test_decimal_max_digits_has_no_effect(self):
  807. Book.objects.all().delete()
  808. a1 = Author.objects.first()
  809. p1 = Publisher.objects.first()
  810. thedate = timezone.now()
  811. for i in range(10):
  812. Book.objects.create(
  813. isbn="abcde{}".format(i), name="none", pages=10, rating=4.0,
  814. price=9999.98, contact=a1, publisher=p1, pubdate=thedate)
  815. book = Book.objects.aggregate(price_sum=Sum('price'))
  816. self.assertEqual(book['price_sum'], Decimal("99999.80"))
  817. def test_nonaggregate_aggregation_throws(self):
  818. with six.assertRaisesRegex(self, TypeError, 'fail is not an aggregate expression'):
  819. Book.objects.aggregate(fail=F('price'))
  820. def test_nonfield_annotation(self):
  821. book = Book.objects.annotate(val=Max(Value(2, output_field=IntegerField()))).first()
  822. self.assertEqual(book.val, 2)
  823. book = Book.objects.annotate(val=Max(Value(2), output_field=IntegerField())).first()
  824. self.assertEqual(book.val, 2)
  825. book = Book.objects.annotate(val=Max(2, output_field=IntegerField())).first()
  826. self.assertEqual(book.val, 2)
  827. def test_missing_output_field_raises_error(self):
  828. with six.assertRaisesRegex(self, FieldError, 'Cannot resolve expression type, unknown output_field'):
  829. Book.objects.annotate(val=Max(2)).first()
  830. def test_annotation_expressions(self):
  831. authors = Author.objects.annotate(combined_ages=Sum(F('age') + F('friends__age'))).order_by('name')
  832. authors2 = Author.objects.annotate(combined_ages=Sum('age') + Sum('friends__age')).order_by('name')
  833. for qs in (authors, authors2):
  834. self.assertEqual(len(qs), 9)
  835. self.assertQuerysetEqual(
  836. qs, [
  837. ('Adrian Holovaty', 132),
  838. ('Brad Dayley', None),
  839. ('Jacob Kaplan-Moss', 129),
  840. ('James Bennett', 63),
  841. ('Jeffrey Forcier', 128),
  842. ('Paul Bissex', 120),
  843. ('Peter Norvig', 103),
  844. ('Stuart Russell', 103),
  845. ('Wesley J. Chun', 176)
  846. ],
  847. lambda a: (a.name, a.combined_ages)
  848. )
  849. def test_aggregation_expressions(self):
  850. a1 = Author.objects.aggregate(av_age=Sum('age') / Count('*'))
  851. a2 = Author.objects.aggregate(av_age=Sum('age') / Count('age'))
  852. a3 = Author.objects.aggregate(av_age=Avg('age'))
  853. self.assertEqual(a1, {'av_age': 37})
  854. self.assertEqual(a2, {'av_age': 37})
  855. self.assertEqual(a3, {'av_age': Approximate(37.4, places=1)})
  856. def test_avg_decimal_field(self):
  857. v = Book.objects.filter(rating=4).aggregate(avg_price=(Avg('price')))['avg_price']
  858. self.assertIsInstance(v, float)
  859. self.assertEqual(v, Approximate(47.39, places=2))
  860. def test_order_of_precedence(self):
  861. p1 = Book.objects.filter(rating=4).aggregate(avg_price=(Avg('price') + 2) * 3)
  862. self.assertEqual(p1, {'avg_price': Approximate(148.18, places=2)})
  863. p2 = Book.objects.filter(rating=4).aggregate(avg_price=Avg('price') + 2 * 3)
  864. self.assertEqual(p2, {'avg_price': Approximate(53.39, places=2)})
  865. def test_combine_different_types(self):
  866. with six.assertRaisesRegex(self, FieldError, 'Expression contains mixed types. You must set output_field'):
  867. Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price')).get(pk=self.b4.pk)
  868. b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
  869. output_field=IntegerField())).get(pk=self.b4.pk)
  870. self.assertEqual(b1.sums, 383)
  871. b2 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
  872. output_field=FloatField())).get(pk=self.b4.pk)
  873. self.assertEqual(b2.sums, 383.69)
  874. b3 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
  875. output_field=DecimalField())).get(pk=self.b4.pk)
  876. self.assertEqual(b3.sums, Approximate(Decimal("383.69"), places=2))
  877. def test_complex_aggregations_require_kwarg(self):
  878. with six.assertRaisesRegex(self, TypeError, 'Complex annotations require an alias'):
  879. Author.objects.annotate(Sum(F('age') + F('friends__age')))
  880. with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'):
  881. Author.objects.aggregate(Sum('age') / Count('age'))
  882. with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'):
  883. Author.objects.aggregate(Sum(1))
  884. def test_aggregate_over_complex_annotation(self):
  885. qs = Author.objects.annotate(
  886. combined_ages=Sum(F('age') + F('friends__age')))
  887. age = qs.aggregate(max_combined_age=Max('combined_ages'))
  888. self.assertEqual(age['max_combined_age'], 176)
  889. age = qs.aggregate(max_combined_age_doubled=Max('combined_ages') * 2)
  890. self.assertEqual(age['max_combined_age_doubled'], 176 * 2)
  891. age = qs.aggregate(
  892. max_combined_age_doubled=Max('combined_ages') + Max('combined_ages'))
  893. self.assertEqual(age['max_combined_age_doubled'], 176 * 2)
  894. age = qs.aggregate(
  895. max_combined_age_doubled=Max('combined_ages') + Max('combined_ages'),
  896. sum_combined_age=Sum('combined_ages'))
  897. self.assertEqual(age['max_combined_age_doubled'], 176 * 2)
  898. self.assertEqual(age['sum_combined_age'], 954)
  899. age = qs.aggregate(
  900. max_combined_age_doubled=Max('combined_ages') + Max('combined_ages'),
  901. sum_combined_age_doubled=Sum('combined_ages') + Sum('combined_ages'))
  902. self.assertEqual(age['max_combined_age_doubled'], 176 * 2)
  903. self.assertEqual(age['sum_combined_age_doubled'], 954 * 2)
  904. def test_values_annotation_with_expression(self):
  905. # ensure the F() is promoted to the group by clause
  906. qs = Author.objects.values('name').annotate(another_age=Sum('age') + F('age'))
  907. a = qs.get(name="Adrian Holovaty")
  908. self.assertEqual(a['another_age'], 68)
  909. qs = qs.annotate(friend_count=Count('friends'))
  910. a = qs.get(name="Adrian Holovaty")
  911. self.assertEqual(a['friend_count'], 2)
  912. qs = qs.annotate(combined_age=Sum('age') + F('friends__age')).filter(
  913. name="Adrian Holovaty").order_by('-combined_age')
  914. self.assertEqual(
  915. list(qs), [
  916. {
  917. "name": 'Adrian Holovaty',
  918. "another_age": 68,
  919. "friend_count": 1,
  920. "combined_age": 69
  921. },
  922. {
  923. "name": 'Adrian Holovaty',
  924. "another_age": 68,
  925. "friend_count": 1,
  926. "combined_age": 63
  927. }
  928. ]
  929. )
  930. vals = qs.values('name', 'combined_age')
  931. self.assertEqual(
  932. list(vals), [
  933. {
  934. "name": 'Adrian Holovaty',
  935. "combined_age": 69
  936. },
  937. {
  938. "name": 'Adrian Holovaty',
  939. "combined_age": 63
  940. }
  941. ]
  942. )
  943. def test_annotate_values_aggregate(self):
  944. alias_age = Author.objects.annotate(
  945. age_alias=F('age')
  946. ).values(
  947. 'age_alias',
  948. ).aggregate(sum_age=Sum('age_alias'))
  949. age = Author.objects.values('age').aggregate(sum_age=Sum('age'))
  950. self.assertEqual(alias_age['sum_age'], age['sum_age'])
  951. def test_annotate_over_annotate(self):
  952. author = Author.objects.annotate(
  953. age_alias=F('age')
  954. ).annotate(
  955. sum_age=Sum('age_alias')
  956. ).get(name="Adrian Holovaty")
  957. other_author = Author.objects.annotate(
  958. sum_age=Sum('age')
  959. ).get(name="Adrian Holovaty")
  960. self.assertEqual(author.sum_age, other_author.sum_age)
  961. def test_annotated_aggregate_over_annotated_aggregate(self):
  962. with self.assertRaisesMessage(FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate"):
  963. Book.objects.annotate(Max('id')).annotate(Sum('id__max'))
  964. class MyMax(Max):
  965. def as_sql(self, compiler, connection):
  966. self.set_source_expressions(self.get_source_expressions()[0:1])
  967. return super(MyMax, self).as_sql(compiler, connection)
  968. with self.assertRaisesMessage(FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate"):
  969. Book.objects.annotate(Max('id')).annotate(my_max=MyMax('id__max', 'price'))
  970. def test_multi_arg_aggregate(self):
  971. class MyMax(Max):
  972. def as_sql(self, compiler, connection):
  973. self.set_source_expressions(self.get_source_expressions()[0:1])
  974. return super(MyMax, self).as_sql(compiler, connection)
  975. with self.assertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
  976. Book.objects.aggregate(MyMax('pages', 'price'))
  977. with self.assertRaisesMessage(TypeError, 'Complex annotations require an alias'):
  978. Book.objects.annotate(MyMax('pages', 'price'))
  979. Book.objects.aggregate(max_field=MyMax('pages', 'price'))
  980. def test_add_implementation(self):
  981. class MySum(Sum):
  982. pass
  983. # test completely changing how the output is rendered
  984. def lower_case_function_override(self, compiler, connection):
  985. sql, params = compiler.compile(self.source_expressions[0])
  986. substitutions = dict(function=self.function.lower(), expressions=sql)
  987. substitutions.update(self.extra)
  988. return self.template % substitutions, params
  989. setattr(MySum, 'as_' + connection.vendor, lower_case_function_override)
  990. qs = Book.objects.annotate(
  991. sums=MySum(F('rating') + F('pages') + F('price'), output_field=IntegerField())
  992. )
  993. self.assertEqual(str(qs.query).count('sum('), 1)
  994. b1 = qs.get(pk=self.b4.pk)
  995. self.assertEqual(b1.sums, 383)
  996. # test changing the dict and delegating
  997. def lower_case_function_super(self, compiler, connection):
  998. self.extra['function'] = self.function.lower()
  999. return super(MySum, self).as_sql(compiler, connection)
  1000. setattr(MySum, 'as_' + connection.vendor, lower_case_function_super)
  1001. qs = Book.objects.annotate(
  1002. sums=MySum(F('rating') + F('pages') + F('price'), output_field=IntegerField())
  1003. )
  1004. self.assertEqual(str(qs.query).count('sum('), 1)
  1005. b1 = qs.get(pk=self.b4.pk)
  1006. self.assertEqual(b1.sums, 383)
  1007. # test overriding all parts of the template
  1008. def be_evil(self, compiler, connection):
  1009. substitutions = dict(function='MAX', expressions='2')
  1010. substitutions.update(self.extra)
  1011. return self.template % substitutions, ()
  1012. setattr(MySum, 'as_' + connection.vendor, be_evil)
  1013. qs = Book.objects.annotate(
  1014. sums=MySum(F('rating') + F('pages') + F('price'), output_field=IntegerField())
  1015. )
  1016. self.assertEqual(str(qs.query).count('MAX('), 1)
  1017. b1 = qs.get(pk=self.b4.pk)
  1018. self.assertEqual(b1.sums, 2)
  1019. def test_complex_values_aggregation(self):
  1020. max_rating = Book.objects.values('rating').aggregate(
  1021. double_max_rating=Max('rating') + Max('rating'))
  1022. self.assertEqual(max_rating['double_max_rating'], 5 * 2)
  1023. max_books_per_rating = Book.objects.values('rating').annotate(
  1024. books_per_rating=Count('id') + 5
  1025. ).aggregate(Max('books_per_rating'))
  1026. self.assertEqual(
  1027. max_books_per_rating,
  1028. {'books_per_rating__max': 3 + 5})
  1029. def test_expression_on_aggregation(self):
  1030. # Create a plain expression
  1031. class Greatest(Func):
  1032. function = 'GREATEST'
  1033. def as_sqlite(self, compiler, connection):
  1034. return super(Greatest, self).as_sql(compiler, connection, function='MAX')
  1035. qs = Publisher.objects.annotate(
  1036. price_or_median=Greatest(Avg('book__rating'), Avg('book__price'))
  1037. ).filter(price_or_median__gte=F('num_awards')).order_by('num_awards')
  1038. self.assertQuerysetEqual(
  1039. qs, [1, 3, 7, 9], lambda v: v.num_awards)
  1040. qs2 = Publisher.objects.annotate(
  1041. rating_or_num_awards=Greatest(Avg('book__rating'), F('num_awards'),
  1042. output_field=FloatField())
  1043. ).filter(rating_or_num_awards__gt=F('num_awards')).order_by('num_awards')
  1044. self.assertQuerysetEqual(
  1045. qs2, [1, 3], lambda v: v.num_awards)