tests.py 36 KB

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