tests.py 45 KB

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