tests.py 42 KB

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