tests.py 36 KB

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