tests.py 45 KB

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