tests.py 44 KB

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