tests.py 45 KB

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