tests.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. import datetime
  2. import pickle
  3. from decimal import Decimal
  4. from operator import attrgetter
  5. from unittest import mock
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.core.exceptions import FieldError
  8. from django.db import connection
  9. from django.db.models import (
  10. Aggregate,
  11. Avg,
  12. Case,
  13. Count,
  14. DecimalField,
  15. F,
  16. IntegerField,
  17. Max,
  18. Q,
  19. StdDev,
  20. Sum,
  21. Value,
  22. Variance,
  23. When,
  24. )
  25. from django.test import TestCase, skipUnlessAnyDBFeature, skipUnlessDBFeature
  26. from django.test.utils import Approximate
  27. from .models import (
  28. Alfa,
  29. Author,
  30. Book,
  31. Bravo,
  32. Charlie,
  33. Clues,
  34. Entries,
  35. HardbackBook,
  36. ItemTag,
  37. Publisher,
  38. SelfRefFK,
  39. Store,
  40. WithManualPK,
  41. )
  42. class AggregationTests(TestCase):
  43. @classmethod
  44. def setUpTestData(cls):
  45. cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34)
  46. cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35)
  47. cls.a3 = Author.objects.create(name="Brad Dayley", age=45)
  48. cls.a4 = Author.objects.create(name="James Bennett", age=29)
  49. cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37)
  50. cls.a6 = Author.objects.create(name="Paul Bissex", age=29)
  51. cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25)
  52. cls.a8 = Author.objects.create(name="Peter Norvig", age=57)
  53. cls.a9 = Author.objects.create(name="Stuart Russell", age=46)
  54. cls.a1.friends.add(cls.a2, cls.a4)
  55. cls.a2.friends.add(cls.a1, cls.a7)
  56. cls.a4.friends.add(cls.a1)
  57. cls.a5.friends.add(cls.a6, cls.a7)
  58. cls.a6.friends.add(cls.a5, cls.a7)
  59. cls.a7.friends.add(cls.a2, cls.a5, cls.a6)
  60. cls.a8.friends.add(cls.a9)
  61. cls.a9.friends.add(cls.a8)
  62. cls.p1 = Publisher.objects.create(name="Apress", num_awards=3)
  63. cls.p2 = Publisher.objects.create(name="Sams", num_awards=1)
  64. cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7)
  65. cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9)
  66. cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0)
  67. cls.b1 = Book.objects.create(
  68. isbn="159059725",
  69. name="The Definitive Guide to Django: Web Development Done Right",
  70. pages=447,
  71. rating=4.5,
  72. price=Decimal("30.00"),
  73. contact=cls.a1,
  74. publisher=cls.p1,
  75. pubdate=datetime.date(2007, 12, 6),
  76. )
  77. cls.b2 = Book.objects.create(
  78. isbn="067232959",
  79. name="Sams Teach Yourself Django in 24 Hours",
  80. pages=528,
  81. rating=3.0,
  82. price=Decimal("23.09"),
  83. contact=cls.a3,
  84. publisher=cls.p2,
  85. pubdate=datetime.date(2008, 3, 3),
  86. )
  87. cls.b3 = Book.objects.create(
  88. isbn="159059996",
  89. name="Practical Django Projects",
  90. pages=300,
  91. rating=4.0,
  92. price=Decimal("29.69"),
  93. contact=cls.a4,
  94. publisher=cls.p1,
  95. pubdate=datetime.date(2008, 6, 23),
  96. )
  97. cls.b4 = Book.objects.create(
  98. isbn="013235613",
  99. name="Python Web Development with Django",
  100. pages=350,
  101. rating=4.0,
  102. price=Decimal("29.69"),
  103. contact=cls.a5,
  104. publisher=cls.p3,
  105. pubdate=datetime.date(2008, 11, 3),
  106. )
  107. cls.b5 = HardbackBook.objects.create(
  108. isbn="013790395",
  109. name="Artificial Intelligence: A Modern Approach",
  110. pages=1132,
  111. rating=4.0,
  112. price=Decimal("82.80"),
  113. contact=cls.a8,
  114. publisher=cls.p3,
  115. pubdate=datetime.date(1995, 1, 15),
  116. weight=4.5,
  117. )
  118. cls.b6 = HardbackBook.objects.create(
  119. isbn="155860191",
  120. name=(
  121. "Paradigms of Artificial Intelligence Programming: Case Studies in "
  122. "Common Lisp"
  123. ),
  124. pages=946,
  125. rating=5.0,
  126. price=Decimal("75.00"),
  127. contact=cls.a8,
  128. publisher=cls.p4,
  129. pubdate=datetime.date(1991, 10, 15),
  130. weight=3.7,
  131. )
  132. cls.b1.authors.add(cls.a1, cls.a2)
  133. cls.b2.authors.add(cls.a3)
  134. cls.b3.authors.add(cls.a4)
  135. cls.b4.authors.add(cls.a5, cls.a6, cls.a7)
  136. cls.b5.authors.add(cls.a8, cls.a9)
  137. cls.b6.authors.add(cls.a8)
  138. s1 = Store.objects.create(
  139. name="Amazon.com",
  140. original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42),
  141. friday_night_closing=datetime.time(23, 59, 59),
  142. )
  143. s2 = Store.objects.create(
  144. name="Books.com",
  145. original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37),
  146. friday_night_closing=datetime.time(23, 59, 59),
  147. )
  148. s3 = Store.objects.create(
  149. name="Mamma and Pappa's Books",
  150. original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14),
  151. friday_night_closing=datetime.time(21, 30),
  152. )
  153. s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6)
  154. s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6)
  155. s3.books.add(cls.b3, cls.b4, cls.b6)
  156. def assertObjectAttrs(self, obj, **kwargs):
  157. for attr, value in kwargs.items():
  158. self.assertEqual(getattr(obj, attr), value)
  159. def test_annotation_with_value(self):
  160. values = (
  161. Book.objects.filter(
  162. name="Practical Django Projects",
  163. )
  164. .annotate(
  165. discount_price=F("price") * 2,
  166. )
  167. .values(
  168. "discount_price",
  169. )
  170. .annotate(sum_discount=Sum("discount_price"))
  171. )
  172. self.assertSequenceEqual(
  173. values,
  174. [{"discount_price": Decimal("59.38"), "sum_discount": Decimal("59.38")}],
  175. )
  176. def test_aggregates_in_where_clause(self):
  177. """
  178. Regression test for #12822: DatabaseError: aggregates not allowed in
  179. WHERE clause
  180. The subselect works and returns results equivalent to a
  181. query with the IDs listed.
  182. Before the corresponding fix for this bug, this test passed in 1.1 and
  183. failed in 1.2-beta (trunk).
  184. """
  185. qs = Book.objects.values("contact").annotate(Max("id"))
  186. qs = qs.order_by("contact").values_list("id__max", flat=True)
  187. # don't do anything with the queryset (qs) before including it as a
  188. # subquery
  189. books = Book.objects.order_by("id")
  190. qs1 = books.filter(id__in=qs)
  191. qs2 = books.filter(id__in=list(qs))
  192. self.assertEqual(list(qs1), list(qs2))
  193. def test_aggregates_in_where_clause_pre_eval(self):
  194. """
  195. Regression test for #12822: DatabaseError: aggregates not allowed in
  196. WHERE clause
  197. Same as the above test, but evaluates the queryset for the subquery
  198. before it's used as a subquery.
  199. Before the corresponding fix for this bug, this test failed in both
  200. 1.1 and 1.2-beta (trunk).
  201. """
  202. qs = Book.objects.values("contact").annotate(Max("id"))
  203. qs = qs.order_by("contact").values_list("id__max", flat=True)
  204. # force the queryset (qs) for the subquery to be evaluated in its
  205. # current state
  206. list(qs)
  207. books = Book.objects.order_by("id")
  208. qs1 = books.filter(id__in=qs)
  209. qs2 = books.filter(id__in=list(qs))
  210. self.assertEqual(list(qs1), list(qs2))
  211. @skipUnlessDBFeature("supports_subqueries_in_group_by")
  212. def test_annotate_with_extra(self):
  213. """
  214. Regression test for #11916: Extra params + aggregation creates
  215. incorrect SQL.
  216. """
  217. # Oracle doesn't support subqueries in group by clause
  218. shortest_book_sql = """
  219. SELECT name
  220. FROM aggregation_regress_book b
  221. WHERE b.publisher_id = aggregation_regress_publisher.id
  222. ORDER BY b.pages
  223. LIMIT 1
  224. """
  225. # tests that this query does not raise a DatabaseError due to the full
  226. # subselect being (erroneously) added to the GROUP BY parameters
  227. qs = Publisher.objects.extra(
  228. select={
  229. "name_of_shortest_book": shortest_book_sql,
  230. }
  231. ).annotate(total_books=Count("book"))
  232. # force execution of the query
  233. list(qs)
  234. def test_aggregate(self):
  235. # Ordering requests are ignored
  236. self.assertEqual(
  237. Author.objects.order_by("name").aggregate(Avg("age")),
  238. {"age__avg": Approximate(37.444, places=1)},
  239. )
  240. # Implicit ordering is also ignored
  241. self.assertEqual(
  242. Book.objects.aggregate(Sum("pages")),
  243. {"pages__sum": 3703},
  244. )
  245. # Baseline results
  246. self.assertEqual(
  247. Book.objects.aggregate(Sum("pages"), Avg("pages")),
  248. {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)},
  249. )
  250. # Empty values query doesn't affect grouping or results
  251. self.assertEqual(
  252. Book.objects.values().aggregate(Sum("pages"), Avg("pages")),
  253. {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)},
  254. )
  255. # Aggregate overrides extra selected column
  256. self.assertEqual(
  257. Book.objects.extra(select={"price_per_page": "price / pages"}).aggregate(
  258. Sum("pages")
  259. ),
  260. {"pages__sum": 3703},
  261. )
  262. def test_annotation(self):
  263. # Annotations get combined with extra select clauses
  264. obj = (
  265. Book.objects.annotate(mean_auth_age=Avg("authors__age"))
  266. .extra(select={"manufacture_cost": "price * .5"})
  267. .get(pk=self.b2.pk)
  268. )
  269. self.assertObjectAttrs(
  270. obj,
  271. contact_id=self.a3.id,
  272. isbn="067232959",
  273. mean_auth_age=45.0,
  274. name="Sams Teach Yourself Django in 24 Hours",
  275. pages=528,
  276. price=Decimal("23.09"),
  277. pubdate=datetime.date(2008, 3, 3),
  278. publisher_id=self.p2.id,
  279. rating=3.0,
  280. )
  281. # Different DB backends return different types for the extra select computation
  282. self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545")))
  283. # Order of the annotate/extra in the query doesn't matter
  284. obj = (
  285. Book.objects.extra(select={"manufacture_cost": "price * .5"})
  286. .annotate(mean_auth_age=Avg("authors__age"))
  287. .get(pk=self.b2.pk)
  288. )
  289. self.assertObjectAttrs(
  290. obj,
  291. contact_id=self.a3.id,
  292. isbn="067232959",
  293. mean_auth_age=45.0,
  294. name="Sams Teach Yourself Django in 24 Hours",
  295. pages=528,
  296. price=Decimal("23.09"),
  297. pubdate=datetime.date(2008, 3, 3),
  298. publisher_id=self.p2.id,
  299. rating=3.0,
  300. )
  301. # Different DB backends return different types for the extra select computation
  302. self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545")))
  303. # Values queries can be combined with annotate and extra
  304. obj = (
  305. Book.objects.annotate(mean_auth_age=Avg("authors__age"))
  306. .extra(select={"manufacture_cost": "price * .5"})
  307. .values()
  308. .get(pk=self.b2.pk)
  309. )
  310. manufacture_cost = obj["manufacture_cost"]
  311. self.assertIn(manufacture_cost, (11.545, Decimal("11.545")))
  312. del obj["manufacture_cost"]
  313. self.assertEqual(
  314. obj,
  315. {
  316. "id": self.b2.id,
  317. "contact_id": self.a3.id,
  318. "isbn": "067232959",
  319. "mean_auth_age": 45.0,
  320. "name": "Sams Teach Yourself Django in 24 Hours",
  321. "pages": 528,
  322. "price": Decimal("23.09"),
  323. "pubdate": datetime.date(2008, 3, 3),
  324. "publisher_id": self.p2.id,
  325. "rating": 3.0,
  326. },
  327. )
  328. # The order of the (empty) values, annotate and extra clauses doesn't
  329. # matter
  330. obj = (
  331. Book.objects.values()
  332. .annotate(mean_auth_age=Avg("authors__age"))
  333. .extra(select={"manufacture_cost": "price * .5"})
  334. .get(pk=self.b2.pk)
  335. )
  336. manufacture_cost = obj["manufacture_cost"]
  337. self.assertIn(manufacture_cost, (11.545, Decimal("11.545")))
  338. del obj["manufacture_cost"]
  339. self.assertEqual(
  340. obj,
  341. {
  342. "id": self.b2.id,
  343. "contact_id": self.a3.id,
  344. "isbn": "067232959",
  345. "mean_auth_age": 45.0,
  346. "name": "Sams Teach Yourself Django in 24 Hours",
  347. "pages": 528,
  348. "price": Decimal("23.09"),
  349. "pubdate": datetime.date(2008, 3, 3),
  350. "publisher_id": self.p2.id,
  351. "rating": 3.0,
  352. },
  353. )
  354. # If the annotation precedes the values clause, it won't be included
  355. # unless it is explicitly named
  356. obj = (
  357. Book.objects.annotate(mean_auth_age=Avg("authors__age"))
  358. .extra(select={"price_per_page": "price / pages"})
  359. .values("name")
  360. .get(pk=self.b1.pk)
  361. )
  362. self.assertEqual(
  363. obj,
  364. {
  365. "name": "The Definitive Guide to Django: Web Development Done Right",
  366. },
  367. )
  368. obj = (
  369. Book.objects.annotate(mean_auth_age=Avg("authors__age"))
  370. .extra(select={"price_per_page": "price / pages"})
  371. .values("name", "mean_auth_age")
  372. .get(pk=self.b1.pk)
  373. )
  374. self.assertEqual(
  375. obj,
  376. {
  377. "mean_auth_age": 34.5,
  378. "name": "The Definitive Guide to Django: Web Development Done Right",
  379. },
  380. )
  381. # If an annotation isn't included in the values, it can still be used
  382. # in a filter
  383. qs = (
  384. Book.objects.annotate(n_authors=Count("authors"))
  385. .values("name")
  386. .filter(n_authors__gt=2)
  387. )
  388. self.assertSequenceEqual(
  389. qs,
  390. [{"name": "Python Web Development with Django"}],
  391. )
  392. # The annotations are added to values output if values() precedes
  393. # annotate()
  394. obj = (
  395. Book.objects.values("name")
  396. .annotate(mean_auth_age=Avg("authors__age"))
  397. .extra(select={"price_per_page": "price / pages"})
  398. .get(pk=self.b1.pk)
  399. )
  400. self.assertEqual(
  401. obj,
  402. {
  403. "mean_auth_age": 34.5,
  404. "name": "The Definitive Guide to Django: Web Development Done Right",
  405. },
  406. )
  407. # All of the objects are getting counted (allow_nulls) and that values
  408. # respects the amount of objects
  409. self.assertEqual(len(Author.objects.annotate(Avg("friends__age")).values()), 9)
  410. # Consecutive calls to annotate accumulate in the query
  411. qs = (
  412. Book.objects.values("price")
  413. .annotate(oldest=Max("authors__age"))
  414. .order_by("oldest", "price")
  415. .annotate(Max("publisher__num_awards"))
  416. )
  417. self.assertSequenceEqual(
  418. qs,
  419. [
  420. {"price": Decimal("30"), "oldest": 35, "publisher__num_awards__max": 3},
  421. {
  422. "price": Decimal("29.69"),
  423. "oldest": 37,
  424. "publisher__num_awards__max": 7,
  425. },
  426. {
  427. "price": Decimal("23.09"),
  428. "oldest": 45,
  429. "publisher__num_awards__max": 1,
  430. },
  431. {"price": Decimal("75"), "oldest": 57, "publisher__num_awards__max": 9},
  432. {
  433. "price": Decimal("82.8"),
  434. "oldest": 57,
  435. "publisher__num_awards__max": 7,
  436. },
  437. ],
  438. )
  439. def test_aggregate_annotation(self):
  440. # Aggregates can be composed over annotations.
  441. # The return type is derived from the composed aggregate
  442. vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
  443. Max("pages"), Max("price"), Sum("num_authors"), Avg("num_authors")
  444. )
  445. self.assertEqual(
  446. vals,
  447. {
  448. "num_authors__sum": 10,
  449. "num_authors__avg": Approximate(1.666, places=2),
  450. "pages__max": 1132,
  451. "price__max": Decimal("82.80"),
  452. },
  453. )
  454. # Regression for #15624 - Missing SELECT columns when using values, annotate
  455. # and aggregate in a single query
  456. self.assertEqual(
  457. Book.objects.annotate(c=Count("authors")).values("c").aggregate(Max("c")),
  458. {"c__max": 3},
  459. )
  460. def test_conditional_aggregate(self):
  461. # Conditional aggregation of a grouped queryset.
  462. self.assertEqual(
  463. Book.objects.annotate(c=Count("authors"))
  464. .values("pk")
  465. .aggregate(test=Sum(Case(When(c__gt=1, then=1))))["test"],
  466. 3,
  467. )
  468. def test_sliced_conditional_aggregate(self):
  469. self.assertEqual(
  470. Author.objects.all()[:5].aggregate(
  471. test=Sum(Case(When(age__lte=35, then=1)))
  472. )["test"],
  473. 3,
  474. )
  475. def test_annotated_conditional_aggregate(self):
  476. annotated_qs = Book.objects.annotate(
  477. discount_price=F("price") * Decimal("0.75")
  478. )
  479. self.assertAlmostEqual(
  480. annotated_qs.aggregate(
  481. test=Avg(
  482. Case(
  483. When(pages__lt=400, then="discount_price"),
  484. output_field=DecimalField(),
  485. )
  486. )
  487. )["test"],
  488. Decimal("22.27"),
  489. places=2,
  490. )
  491. def test_distinct_conditional_aggregate(self):
  492. self.assertEqual(
  493. Book.objects.distinct().aggregate(
  494. test=Avg(
  495. Case(
  496. When(price=Decimal("29.69"), then="pages"),
  497. output_field=IntegerField(),
  498. )
  499. )
  500. )["test"],
  501. 325,
  502. )
  503. def test_conditional_aggregate_on_complex_condition(self):
  504. self.assertEqual(
  505. Book.objects.distinct().aggregate(
  506. test=Avg(
  507. Case(
  508. When(
  509. Q(price__gte=Decimal("29")) & Q(price__lt=Decimal("30")),
  510. then="pages",
  511. ),
  512. output_field=IntegerField(),
  513. )
  514. )
  515. )["test"],
  516. 325,
  517. )
  518. def test_decimal_aggregate_annotation_filter(self):
  519. """
  520. Filtering on an aggregate annotation with Decimal values should work.
  521. Requires special handling on SQLite (#18247).
  522. """
  523. self.assertEqual(
  524. len(
  525. Author.objects.annotate(sum=Sum("book_contact_set__price")).filter(
  526. sum__gt=Decimal(40)
  527. )
  528. ),
  529. 1,
  530. )
  531. self.assertEqual(
  532. len(
  533. Author.objects.annotate(sum=Sum("book_contact_set__price")).filter(
  534. sum__lte=Decimal(40)
  535. )
  536. ),
  537. 4,
  538. )
  539. def test_field_error(self):
  540. # Bad field requests in aggregates are caught and reported
  541. msg = (
  542. "Cannot resolve keyword 'foo' into field. Choices are: authors, "
  543. "contact, contact_id, hardbackbook, id, isbn, name, pages, price, "
  544. "pubdate, publisher, publisher_id, rating, store, tags"
  545. )
  546. with self.assertRaisesMessage(FieldError, msg):
  547. Book.objects.aggregate(num_authors=Count("foo"))
  548. with self.assertRaisesMessage(FieldError, msg):
  549. Book.objects.annotate(num_authors=Count("foo"))
  550. msg = (
  551. "Cannot resolve keyword 'foo' into field. Choices are: authors, "
  552. "contact, contact_id, hardbackbook, id, isbn, name, num_authors, "
  553. "pages, price, pubdate, publisher, publisher_id, rating, store, tags"
  554. )
  555. with self.assertRaisesMessage(FieldError, msg):
  556. Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
  557. Max("foo")
  558. )
  559. def test_more(self):
  560. # Old-style count aggregations can be mixed with new-style
  561. self.assertEqual(Book.objects.annotate(num_authors=Count("authors")).count(), 6)
  562. # Non-ordinal, non-computed Aggregates over annotations correctly
  563. # inherit the annotation's internal type if the annotation is ordinal
  564. # or computed
  565. vals = Book.objects.annotate(num_authors=Count("authors")).aggregate(
  566. Max("num_authors")
  567. )
  568. self.assertEqual(vals, {"num_authors__max": 3})
  569. vals = Publisher.objects.annotate(avg_price=Avg("book__price")).aggregate(
  570. Max("avg_price")
  571. )
  572. self.assertEqual(vals, {"avg_price__max": 75.0})
  573. # Aliases are quoted to protected aliases that might be reserved names
  574. vals = Book.objects.aggregate(number=Max("pages"), select=Max("pages"))
  575. self.assertEqual(vals, {"number": 1132, "select": 1132})
  576. # Regression for #10064: select_related() plays nice with aggregates
  577. obj = (
  578. Book.objects.select_related("publisher")
  579. .annotate(num_authors=Count("authors"))
  580. .values()
  581. .get(isbn="013790395")
  582. )
  583. self.assertEqual(
  584. obj,
  585. {
  586. "contact_id": self.a8.id,
  587. "id": self.b5.id,
  588. "isbn": "013790395",
  589. "name": "Artificial Intelligence: A Modern Approach",
  590. "num_authors": 2,
  591. "pages": 1132,
  592. "price": Decimal("82.8"),
  593. "pubdate": datetime.date(1995, 1, 15),
  594. "publisher_id": self.p3.id,
  595. "rating": 4.0,
  596. },
  597. )
  598. # Regression for #10010: exclude on an aggregate field is correctly
  599. # negated
  600. self.assertEqual(len(Book.objects.annotate(num_authors=Count("authors"))), 6)
  601. self.assertEqual(
  602. len(
  603. Book.objects.annotate(num_authors=Count("authors")).filter(
  604. num_authors__gt=2
  605. )
  606. ),
  607. 1,
  608. )
  609. self.assertEqual(
  610. len(
  611. Book.objects.annotate(num_authors=Count("authors")).exclude(
  612. num_authors__gt=2
  613. )
  614. ),
  615. 5,
  616. )
  617. self.assertEqual(
  618. len(
  619. Book.objects.annotate(num_authors=Count("authors"))
  620. .filter(num_authors__lt=3)
  621. .exclude(num_authors__lt=2)
  622. ),
  623. 2,
  624. )
  625. self.assertEqual(
  626. len(
  627. Book.objects.annotate(num_authors=Count("authors"))
  628. .exclude(num_authors__lt=2)
  629. .filter(num_authors__lt=3)
  630. ),
  631. 2,
  632. )
  633. def test_aggregate_fexpr(self):
  634. # Aggregates can be used with F() expressions
  635. # ... where the F() is pushed into the HAVING clause
  636. qs = (
  637. Publisher.objects.annotate(num_books=Count("book"))
  638. .filter(num_books__lt=F("num_awards") / 2)
  639. .order_by("name")
  640. .values("name", "num_books", "num_awards")
  641. )
  642. self.assertSequenceEqual(
  643. qs,
  644. [
  645. {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9},
  646. {"num_books": 2, "name": "Prentice Hall", "num_awards": 7},
  647. ],
  648. )
  649. qs = (
  650. Publisher.objects.annotate(num_books=Count("book"))
  651. .exclude(num_books__lt=F("num_awards") / 2)
  652. .order_by("name")
  653. .values("name", "num_books", "num_awards")
  654. )
  655. self.assertSequenceEqual(
  656. qs,
  657. [
  658. {"num_books": 2, "name": "Apress", "num_awards": 3},
  659. {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0},
  660. {"num_books": 1, "name": "Sams", "num_awards": 1},
  661. ],
  662. )
  663. # ... and where the F() references an aggregate
  664. qs = (
  665. Publisher.objects.annotate(num_books=Count("book"))
  666. .filter(num_awards__gt=2 * F("num_books"))
  667. .order_by("name")
  668. .values("name", "num_books", "num_awards")
  669. )
  670. self.assertSequenceEqual(
  671. qs,
  672. [
  673. {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9},
  674. {"num_books": 2, "name": "Prentice Hall", "num_awards": 7},
  675. ],
  676. )
  677. qs = (
  678. Publisher.objects.annotate(num_books=Count("book"))
  679. .exclude(num_books__lt=F("num_awards") / 2)
  680. .order_by("name")
  681. .values("name", "num_books", "num_awards")
  682. )
  683. self.assertSequenceEqual(
  684. qs,
  685. [
  686. {"num_books": 2, "name": "Apress", "num_awards": 3},
  687. {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0},
  688. {"num_books": 1, "name": "Sams", "num_awards": 1},
  689. ],
  690. )
  691. def test_db_col_table(self):
  692. # Tests on fields with non-default table and column names.
  693. qs = Clues.objects.values("EntryID__Entry").annotate(
  694. Appearances=Count("EntryID"), Distinct_Clues=Count("Clue", distinct=True)
  695. )
  696. self.assertQuerysetEqual(qs, [])
  697. qs = Entries.objects.annotate(clue_count=Count("clues__ID"))
  698. self.assertQuerysetEqual(qs, [])
  699. def test_boolean_conversion(self):
  700. # Aggregates mixed up ordering of columns for backend's convert_values
  701. # method. Refs #21126.
  702. e = Entries.objects.create(Entry="foo")
  703. c = Clues.objects.create(EntryID=e, Clue="bar")
  704. qs = Clues.objects.select_related("EntryID").annotate(Count("ID"))
  705. self.assertSequenceEqual(qs, [c])
  706. self.assertEqual(qs[0].EntryID, e)
  707. self.assertIs(qs[0].EntryID.Exclude, False)
  708. def test_empty(self):
  709. # Regression for #10089: Check handling of empty result sets with
  710. # aggregates
  711. self.assertEqual(Book.objects.filter(id__in=[]).count(), 0)
  712. vals = Book.objects.filter(id__in=[]).aggregate(
  713. num_authors=Count("authors"),
  714. avg_authors=Avg("authors"),
  715. max_authors=Max("authors"),
  716. max_price=Max("price"),
  717. max_rating=Max("rating"),
  718. )
  719. self.assertEqual(
  720. vals,
  721. {
  722. "max_authors": None,
  723. "max_rating": None,
  724. "num_authors": 0,
  725. "avg_authors": None,
  726. "max_price": None,
  727. },
  728. )
  729. qs = (
  730. Publisher.objects.filter(name="Jonno's House of Books")
  731. .annotate(
  732. num_authors=Count("book__authors"),
  733. avg_authors=Avg("book__authors"),
  734. max_authors=Max("book__authors"),
  735. max_price=Max("book__price"),
  736. max_rating=Max("book__rating"),
  737. )
  738. .values()
  739. )
  740. self.assertSequenceEqual(
  741. qs,
  742. [
  743. {
  744. "max_authors": None,
  745. "name": "Jonno's House of Books",
  746. "num_awards": 0,
  747. "max_price": None,
  748. "num_authors": 0,
  749. "max_rating": None,
  750. "id": self.p5.id,
  751. "avg_authors": None,
  752. }
  753. ],
  754. )
  755. def test_more_more(self):
  756. # Regression for #10113 - Fields mentioned in order_by() must be
  757. # included in the GROUP BY. This only becomes a problem when the
  758. # order_by introduces a new join.
  759. self.assertQuerysetEqual(
  760. Book.objects.annotate(num_authors=Count("authors")).order_by(
  761. "publisher__name", "name"
  762. ),
  763. [
  764. "Practical Django Projects",
  765. "The Definitive Guide to Django: Web Development Done Right",
  766. "Paradigms of Artificial Intelligence Programming: Case Studies in "
  767. "Common Lisp",
  768. "Artificial Intelligence: A Modern Approach",
  769. "Python Web Development with Django",
  770. "Sams Teach Yourself Django in 24 Hours",
  771. ],
  772. lambda b: b.name,
  773. )
  774. # Regression for #10127 - Empty select_related() works with annotate
  775. qs = (
  776. Book.objects.filter(rating__lt=4.5)
  777. .select_related()
  778. .annotate(Avg("authors__age"))
  779. .order_by("name")
  780. )
  781. self.assertQuerysetEqual(
  782. qs,
  783. [
  784. (
  785. "Artificial Intelligence: A Modern Approach",
  786. 51.5,
  787. "Prentice Hall",
  788. "Peter Norvig",
  789. ),
  790. ("Practical Django Projects", 29.0, "Apress", "James Bennett"),
  791. (
  792. "Python Web Development with Django",
  793. Approximate(30.333, places=2),
  794. "Prentice Hall",
  795. "Jeffrey Forcier",
  796. ),
  797. ("Sams Teach Yourself Django in 24 Hours", 45.0, "Sams", "Brad Dayley"),
  798. ],
  799. lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name),
  800. )
  801. # Regression for #10132 - If the values() clause only mentioned extra
  802. # (select=) columns, those columns are used for grouping
  803. qs = (
  804. Book.objects.extra(select={"pub": "publisher_id"})
  805. .values("pub")
  806. .annotate(Count("id"))
  807. .order_by("pub")
  808. )
  809. self.assertSequenceEqual(
  810. qs,
  811. [
  812. {"pub": self.p1.id, "id__count": 2},
  813. {"pub": self.p2.id, "id__count": 1},
  814. {"pub": self.p3.id, "id__count": 2},
  815. {"pub": self.p4.id, "id__count": 1},
  816. ],
  817. )
  818. qs = (
  819. Book.objects.extra(select={"pub": "publisher_id", "foo": "pages"})
  820. .values("pub")
  821. .annotate(Count("id"))
  822. .order_by("pub")
  823. )
  824. self.assertSequenceEqual(
  825. qs,
  826. [
  827. {"pub": self.p1.id, "id__count": 2},
  828. {"pub": self.p2.id, "id__count": 1},
  829. {"pub": self.p3.id, "id__count": 2},
  830. {"pub": self.p4.id, "id__count": 1},
  831. ],
  832. )
  833. # Regression for #10182 - Queries with aggregate calls are correctly
  834. # realiased when used in a subquery
  835. ids = (
  836. Book.objects.filter(pages__gt=100)
  837. .annotate(n_authors=Count("authors"))
  838. .filter(n_authors__gt=2)
  839. .order_by("n_authors")
  840. )
  841. self.assertQuerysetEqual(
  842. Book.objects.filter(id__in=ids),
  843. [
  844. "Python Web Development with Django",
  845. ],
  846. lambda b: b.name,
  847. )
  848. # Regression for #15709 - Ensure each group_by field only exists once
  849. # per query
  850. qstr = str(
  851. Book.objects.values("publisher")
  852. .annotate(max_pages=Max("pages"))
  853. .order_by()
  854. .query
  855. )
  856. # There is just one GROUP BY clause (zero commas means at most one clause).
  857. self.assertEqual(qstr[qstr.index("GROUP BY") :].count(", "), 0)
  858. def test_duplicate_alias(self):
  859. # Regression for #11256 - duplicating a default alias raises ValueError.
  860. msg = (
  861. "The named annotation 'authors__age__avg' conflicts with "
  862. "the default name for another annotation."
  863. )
  864. with self.assertRaisesMessage(ValueError, msg):
  865. Book.objects.annotate(
  866. Avg("authors__age"), authors__age__avg=Avg("authors__age")
  867. )
  868. def test_field_name_conflict(self):
  869. # Regression for #11256 - providing an aggregate name
  870. # that conflicts with a field name on the model raises ValueError
  871. msg = "The annotation 'age' conflicts with a field on the model."
  872. with self.assertRaisesMessage(ValueError, msg):
  873. Author.objects.annotate(age=Avg("friends__age"))
  874. def test_m2m_name_conflict(self):
  875. # Regression for #11256 - providing an aggregate name
  876. # that conflicts with an m2m name on the model raises ValueError
  877. msg = "The annotation 'friends' conflicts with a field on the model."
  878. with self.assertRaisesMessage(ValueError, msg):
  879. Author.objects.annotate(friends=Count("friends"))
  880. def test_fk_attname_conflict(self):
  881. msg = "The annotation 'contact_id' conflicts with a field on the model."
  882. with self.assertRaisesMessage(ValueError, msg):
  883. Book.objects.annotate(contact_id=F("publisher_id"))
  884. def test_values_queryset_non_conflict(self):
  885. # If you're using a values query set, some potential conflicts are
  886. # avoided.
  887. # age is a field on Author, so it shouldn't be allowed as an aggregate.
  888. # But age isn't included in values(), so it is.
  889. results = (
  890. Author.objects.values("name")
  891. .annotate(age=Count("book_contact_set"))
  892. .order_by("name")
  893. )
  894. self.assertEqual(len(results), 9)
  895. self.assertEqual(results[0]["name"], "Adrian Holovaty")
  896. self.assertEqual(results[0]["age"], 1)
  897. # Same problem, but aggregating over m2m fields
  898. results = (
  899. Author.objects.values("name")
  900. .annotate(age=Avg("friends__age"))
  901. .order_by("name")
  902. )
  903. self.assertEqual(len(results), 9)
  904. self.assertEqual(results[0]["name"], "Adrian Holovaty")
  905. self.assertEqual(results[0]["age"], 32.0)
  906. # Same problem, but colliding with an m2m field
  907. results = (
  908. Author.objects.values("name")
  909. .annotate(friends=Count("friends"))
  910. .order_by("name")
  911. )
  912. self.assertEqual(len(results), 9)
  913. self.assertEqual(results[0]["name"], "Adrian Holovaty")
  914. self.assertEqual(results[0]["friends"], 2)
  915. def test_reverse_relation_name_conflict(self):
  916. # Regression for #11256 - providing an aggregate name
  917. # that conflicts with a reverse-related name on the model raises ValueError
  918. msg = "The annotation 'book_contact_set' conflicts with a field on the model."
  919. with self.assertRaisesMessage(ValueError, msg):
  920. Author.objects.annotate(book_contact_set=Avg("friends__age"))
  921. def test_pickle(self):
  922. # Regression for #10197 -- Queries with aggregates can be pickled.
  923. # First check that pickling is possible at all. No crash = success
  924. qs = Book.objects.annotate(num_authors=Count("authors"))
  925. pickle.dumps(qs)
  926. # Then check that the round trip works.
  927. query = qs.query.get_compiler(qs.db).as_sql()[0]
  928. qs2 = pickle.loads(pickle.dumps(qs))
  929. self.assertEqual(
  930. qs2.query.get_compiler(qs2.db).as_sql()[0],
  931. query,
  932. )
  933. def test_more_more_more(self):
  934. # Regression for #10199 - Aggregate calls clone the original query so
  935. # the original query can still be used
  936. books = Book.objects.all()
  937. books.aggregate(Avg("authors__age"))
  938. self.assertQuerysetEqual(
  939. books.all(),
  940. [
  941. "Artificial Intelligence: A Modern Approach",
  942. "Paradigms of Artificial Intelligence Programming: Case Studies in "
  943. "Common Lisp",
  944. "Practical Django Projects",
  945. "Python Web Development with Django",
  946. "Sams Teach Yourself Django in 24 Hours",
  947. "The Definitive Guide to Django: Web Development Done Right",
  948. ],
  949. lambda b: b.name,
  950. )
  951. # Regression for #10248 - Annotations work with dates()
  952. qs = (
  953. Book.objects.annotate(num_authors=Count("authors"))
  954. .filter(num_authors=2)
  955. .dates("pubdate", "day")
  956. )
  957. self.assertSequenceEqual(
  958. qs,
  959. [
  960. datetime.date(1995, 1, 15),
  961. datetime.date(2007, 12, 6),
  962. ],
  963. )
  964. # Regression for #10290 - extra selects with parameters can be used for
  965. # grouping.
  966. qs = (
  967. Book.objects.annotate(mean_auth_age=Avg("authors__age"))
  968. .extra(select={"sheets": "(pages + %s) / %s"}, select_params=[1, 2])
  969. .order_by("sheets")
  970. .values("sheets")
  971. )
  972. self.assertQuerysetEqual(
  973. qs, [150, 175, 224, 264, 473, 566], lambda b: int(b["sheets"])
  974. )
  975. # Regression for 10425 - annotations don't get in the way of a count()
  976. # clause
  977. self.assertEqual(
  978. Book.objects.values("publisher").annotate(Count("publisher")).count(), 4
  979. )
  980. self.assertEqual(
  981. Book.objects.annotate(Count("publisher")).values("publisher").count(), 6
  982. )
  983. # Note: intentionally no order_by(), that case needs tests, too.
  984. publishers = Publisher.objects.filter(id__in=[self.p1.id, self.p2.id])
  985. self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
  986. publishers = publishers.annotate(n_books=Count("book"))
  987. sorted_publishers = sorted(publishers, key=lambda x: x.name)
  988. self.assertEqual(sorted_publishers[0].n_books, 2)
  989. self.assertEqual(sorted_publishers[1].n_books, 1)
  990. self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
  991. books = Book.objects.filter(publisher__in=publishers)
  992. self.assertQuerysetEqual(
  993. books,
  994. [
  995. "Practical Django Projects",
  996. "Sams Teach Yourself Django in 24 Hours",
  997. "The Definitive Guide to Django: Web Development Done Right",
  998. ],
  999. lambda b: b.name,
  1000. )
  1001. self.assertEqual(sorted(p.name for p in publishers), ["Apress", "Sams"])
  1002. # Regression for 10666 - inherited fields work with annotations and
  1003. # aggregations
  1004. self.assertEqual(
  1005. HardbackBook.objects.aggregate(n_pages=Sum("book_ptr__pages")),
  1006. {"n_pages": 2078},
  1007. )
  1008. self.assertEqual(
  1009. HardbackBook.objects.aggregate(n_pages=Sum("pages")),
  1010. {"n_pages": 2078},
  1011. )
  1012. qs = (
  1013. HardbackBook.objects.annotate(
  1014. n_authors=Count("book_ptr__authors"),
  1015. )
  1016. .values("name", "n_authors")
  1017. .order_by("name")
  1018. )
  1019. self.assertSequenceEqual(
  1020. qs,
  1021. [
  1022. {"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
  1023. {
  1024. "n_authors": 1,
  1025. "name": (
  1026. "Paradigms of Artificial Intelligence Programming: Case "
  1027. "Studies in Common Lisp"
  1028. ),
  1029. },
  1030. ],
  1031. )
  1032. qs = (
  1033. HardbackBook.objects.annotate(n_authors=Count("authors"))
  1034. .values("name", "n_authors")
  1035. .order_by("name")
  1036. )
  1037. self.assertSequenceEqual(
  1038. qs,
  1039. [
  1040. {"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
  1041. {
  1042. "n_authors": 1,
  1043. "name": (
  1044. "Paradigms of Artificial Intelligence Programming: Case "
  1045. "Studies in Common Lisp"
  1046. ),
  1047. },
  1048. ],
  1049. )
  1050. # Regression for #10766 - Shouldn't be able to reference an aggregate
  1051. # fields in an aggregate() call.
  1052. msg = "Cannot compute Avg('mean_age'): 'mean_age' is an aggregate"
  1053. with self.assertRaisesMessage(FieldError, msg):
  1054. Book.objects.annotate(mean_age=Avg("authors__age")).annotate(
  1055. Avg("mean_age")
  1056. )
  1057. def test_empty_filter_count(self):
  1058. self.assertEqual(
  1059. Author.objects.filter(id__in=[]).annotate(Count("friends")).count(), 0
  1060. )
  1061. def test_empty_filter_aggregate(self):
  1062. self.assertEqual(
  1063. Author.objects.filter(id__in=[])
  1064. .annotate(Count("friends"))
  1065. .aggregate(Count("pk")),
  1066. {"pk__count": 0},
  1067. )
  1068. def test_none_call_before_aggregate(self):
  1069. # Regression for #11789
  1070. self.assertEqual(
  1071. Author.objects.none().aggregate(Avg("age")), {"age__avg": None}
  1072. )
  1073. def test_annotate_and_join(self):
  1074. self.assertEqual(
  1075. Author.objects.annotate(c=Count("friends__name"))
  1076. .exclude(friends__name="Joe")
  1077. .count(),
  1078. Author.objects.count(),
  1079. )
  1080. def test_f_expression_annotation(self):
  1081. # Books with less than 200 pages per author.
  1082. qs = (
  1083. Book.objects.values("name")
  1084. .annotate(n_authors=Count("authors"))
  1085. .filter(pages__lt=F("n_authors") * 200)
  1086. .values_list("pk")
  1087. )
  1088. self.assertQuerysetEqual(
  1089. Book.objects.filter(pk__in=qs),
  1090. ["Python Web Development with Django"],
  1091. attrgetter("name"),
  1092. )
  1093. def test_values_annotate_values(self):
  1094. qs = (
  1095. Book.objects.values("name")
  1096. .annotate(n_authors=Count("authors"))
  1097. .values_list("pk", flat=True)
  1098. .order_by("name")
  1099. )
  1100. self.assertEqual(list(qs), list(Book.objects.values_list("pk", flat=True)))
  1101. def test_having_group_by(self):
  1102. # When a field occurs on the LHS of a HAVING clause that it
  1103. # appears correctly in the GROUP BY clause
  1104. qs = (
  1105. Book.objects.values_list("name")
  1106. .annotate(n_authors=Count("authors"))
  1107. .filter(pages__gt=F("n_authors"))
  1108. .values_list("name", flat=True)
  1109. .order_by("name")
  1110. )
  1111. # Results should be the same, all Books have more pages than authors
  1112. self.assertEqual(list(qs), list(Book.objects.values_list("name", flat=True)))
  1113. def test_values_list_annotation_args_ordering(self):
  1114. """
  1115. Annotate *args ordering should be preserved in values_list results.
  1116. **kwargs comes after *args.
  1117. Regression test for #23659.
  1118. """
  1119. books = (
  1120. Book.objects.values_list("publisher__name")
  1121. .annotate(
  1122. Count("id"), Avg("price"), Avg("authors__age"), avg_pgs=Avg("pages")
  1123. )
  1124. .order_by("-publisher__name")
  1125. )
  1126. self.assertEqual(books[0], ("Sams", 1, Decimal("23.09"), 45.0, 528.0))
  1127. def test_annotation_disjunction(self):
  1128. qs = (
  1129. Book.objects.annotate(n_authors=Count("authors"))
  1130. .filter(Q(n_authors=2) | Q(name="Python Web Development with Django"))
  1131. .order_by("name")
  1132. )
  1133. self.assertQuerysetEqual(
  1134. qs,
  1135. [
  1136. "Artificial Intelligence: A Modern Approach",
  1137. "Python Web Development with Django",
  1138. "The Definitive Guide to Django: Web Development Done Right",
  1139. ],
  1140. attrgetter("name"),
  1141. )
  1142. qs = (
  1143. Book.objects.annotate(n_authors=Count("authors")).filter(
  1144. Q(name="The Definitive Guide to Django: Web Development Done Right")
  1145. | (
  1146. Q(name="Artificial Intelligence: A Modern Approach")
  1147. & Q(n_authors=3)
  1148. )
  1149. )
  1150. ).order_by("name")
  1151. self.assertQuerysetEqual(
  1152. qs,
  1153. [
  1154. "The Definitive Guide to Django: Web Development Done Right",
  1155. ],
  1156. attrgetter("name"),
  1157. )
  1158. qs = (
  1159. Publisher.objects.annotate(
  1160. rating_sum=Sum("book__rating"), book_count=Count("book")
  1161. )
  1162. .filter(Q(rating_sum__gt=5.5) | Q(rating_sum__isnull=True))
  1163. .order_by("pk")
  1164. )
  1165. self.assertQuerysetEqual(
  1166. qs,
  1167. [
  1168. "Apress",
  1169. "Prentice Hall",
  1170. "Jonno's House of Books",
  1171. ],
  1172. attrgetter("name"),
  1173. )
  1174. qs = (
  1175. Publisher.objects.annotate(
  1176. rating_sum=Sum("book__rating"), book_count=Count("book")
  1177. )
  1178. .filter(Q(rating_sum__gt=F("book_count")) | Q(rating_sum=None))
  1179. .order_by("num_awards")
  1180. )
  1181. self.assertQuerysetEqual(
  1182. qs,
  1183. [
  1184. "Jonno's House of Books",
  1185. "Sams",
  1186. "Apress",
  1187. "Prentice Hall",
  1188. "Morgan Kaufmann",
  1189. ],
  1190. attrgetter("name"),
  1191. )
  1192. def test_quoting_aggregate_order_by(self):
  1193. qs = (
  1194. Book.objects.filter(name="Python Web Development with Django")
  1195. .annotate(authorCount=Count("authors"))
  1196. .order_by("authorCount")
  1197. )
  1198. self.assertQuerysetEqual(
  1199. qs,
  1200. [
  1201. ("Python Web Development with Django", 3),
  1202. ],
  1203. lambda b: (b.name, b.authorCount),
  1204. )
  1205. def test_stddev(self):
  1206. self.assertEqual(
  1207. Book.objects.aggregate(StdDev("pages")),
  1208. {"pages__stddev": Approximate(311.46, 1)},
  1209. )
  1210. self.assertEqual(
  1211. Book.objects.aggregate(StdDev("rating")),
  1212. {"rating__stddev": Approximate(0.60, 1)},
  1213. )
  1214. self.assertEqual(
  1215. Book.objects.aggregate(StdDev("price")),
  1216. {"price__stddev": Approximate(Decimal("24.16"), 2)},
  1217. )
  1218. self.assertEqual(
  1219. Book.objects.aggregate(StdDev("pages", sample=True)),
  1220. {"pages__stddev": Approximate(341.19, 2)},
  1221. )
  1222. self.assertEqual(
  1223. Book.objects.aggregate(StdDev("rating", sample=True)),
  1224. {"rating__stddev": Approximate(0.66, 2)},
  1225. )
  1226. self.assertEqual(
  1227. Book.objects.aggregate(StdDev("price", sample=True)),
  1228. {"price__stddev": Approximate(Decimal("26.46"), 1)},
  1229. )
  1230. self.assertEqual(
  1231. Book.objects.aggregate(Variance("pages")),
  1232. {"pages__variance": Approximate(97010.80, 1)},
  1233. )
  1234. self.assertEqual(
  1235. Book.objects.aggregate(Variance("rating")),
  1236. {"rating__variance": Approximate(0.36, 1)},
  1237. )
  1238. self.assertEqual(
  1239. Book.objects.aggregate(Variance("price")),
  1240. {"price__variance": Approximate(Decimal("583.77"), 1)},
  1241. )
  1242. self.assertEqual(
  1243. Book.objects.aggregate(Variance("pages", sample=True)),
  1244. {"pages__variance": Approximate(116412.96, 1)},
  1245. )
  1246. self.assertEqual(
  1247. Book.objects.aggregate(Variance("rating", sample=True)),
  1248. {"rating__variance": Approximate(0.44, 2)},
  1249. )
  1250. self.assertEqual(
  1251. Book.objects.aggregate(Variance("price", sample=True)),
  1252. {"price__variance": Approximate(Decimal("700.53"), 2)},
  1253. )
  1254. def test_filtering_by_annotation_name(self):
  1255. # Regression test for #14476
  1256. # The name of the explicitly provided annotation name in this case
  1257. # poses no problem
  1258. qs = (
  1259. Author.objects.annotate(book_cnt=Count("book"))
  1260. .filter(book_cnt=2)
  1261. .order_by("name")
  1262. )
  1263. self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
  1264. # Neither in this case
  1265. qs = (
  1266. Author.objects.annotate(book_count=Count("book"))
  1267. .filter(book_count=2)
  1268. .order_by("name")
  1269. )
  1270. self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
  1271. # This case used to fail because the ORM couldn't resolve the
  1272. # automatically generated annotation name `book__count`
  1273. qs = (
  1274. Author.objects.annotate(Count("book"))
  1275. .filter(book__count=2)
  1276. .order_by("name")
  1277. )
  1278. self.assertQuerysetEqual(qs, ["Peter Norvig"], lambda b: b.name)
  1279. # Referencing the auto-generated name in an aggregate() also works.
  1280. self.assertEqual(
  1281. Author.objects.annotate(Count("book")).aggregate(Max("book__count")),
  1282. {"book__count__max": 2},
  1283. )
  1284. def test_annotate_joins(self):
  1285. """
  1286. The base table's join isn't promoted to LOUTER. This could
  1287. cause the query generation to fail if there is an exclude() for fk-field
  1288. in the query, too. Refs #19087.
  1289. """
  1290. qs = Book.objects.annotate(n=Count("pk"))
  1291. self.assertIs(qs.query.alias_map["aggregation_regress_book"].join_type, None)
  1292. # The query executes without problems.
  1293. self.assertEqual(len(qs.exclude(publisher=-1)), 6)
  1294. @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
  1295. def test_aggregate_duplicate_columns(self):
  1296. # Regression test for #17144
  1297. results = Author.objects.annotate(num_contacts=Count("book_contact_set"))
  1298. # There should only be one GROUP BY clause, for the `id` column.
  1299. # `name` and `age` should not be grouped on.
  1300. _, _, group_by = results.query.get_compiler(using="default").pre_sql_setup()
  1301. self.assertEqual(len(group_by), 1)
  1302. self.assertIn("id", group_by[0][0])
  1303. self.assertNotIn("name", group_by[0][0])
  1304. self.assertNotIn("age", group_by[0][0])
  1305. self.assertEqual(
  1306. [(a.name, a.num_contacts) for a in results.order_by("name")],
  1307. [
  1308. ("Adrian Holovaty", 1),
  1309. ("Brad Dayley", 1),
  1310. ("Jacob Kaplan-Moss", 0),
  1311. ("James Bennett", 1),
  1312. ("Jeffrey Forcier", 1),
  1313. ("Paul Bissex", 0),
  1314. ("Peter Norvig", 2),
  1315. ("Stuart Russell", 0),
  1316. ("Wesley J. Chun", 0),
  1317. ],
  1318. )
  1319. @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
  1320. def test_aggregate_duplicate_columns_only(self):
  1321. # Works with only() too.
  1322. results = Author.objects.only("id", "name").annotate(
  1323. num_contacts=Count("book_contact_set")
  1324. )
  1325. _, _, grouping = results.query.get_compiler(using="default").pre_sql_setup()
  1326. self.assertEqual(len(grouping), 1)
  1327. self.assertIn("id", grouping[0][0])
  1328. self.assertNotIn("name", grouping[0][0])
  1329. self.assertNotIn("age", grouping[0][0])
  1330. self.assertEqual(
  1331. [(a.name, a.num_contacts) for a in results.order_by("name")],
  1332. [
  1333. ("Adrian Holovaty", 1),
  1334. ("Brad Dayley", 1),
  1335. ("Jacob Kaplan-Moss", 0),
  1336. ("James Bennett", 1),
  1337. ("Jeffrey Forcier", 1),
  1338. ("Paul Bissex", 0),
  1339. ("Peter Norvig", 2),
  1340. ("Stuart Russell", 0),
  1341. ("Wesley J. Chun", 0),
  1342. ],
  1343. )
  1344. @skipUnlessAnyDBFeature("allows_group_by_pk", "allows_group_by_selected_pks")
  1345. def test_aggregate_duplicate_columns_select_related(self):
  1346. # And select_related()
  1347. results = Book.objects.select_related("contact").annotate(
  1348. num_authors=Count("authors")
  1349. )
  1350. _, _, grouping = results.query.get_compiler(using="default").pre_sql_setup()
  1351. # In the case of `group_by_selected_pks` we also group by contact.id
  1352. # because of the select_related.
  1353. self.assertEqual(
  1354. len(grouping), 1 if connection.features.allows_group_by_pk else 2
  1355. )
  1356. self.assertIn("id", grouping[0][0])
  1357. self.assertNotIn("name", grouping[0][0])
  1358. self.assertNotIn("contact", grouping[0][0])
  1359. self.assertEqual(
  1360. [(b.name, b.num_authors) for b in results.order_by("name")],
  1361. [
  1362. ("Artificial Intelligence: A Modern Approach", 2),
  1363. (
  1364. "Paradigms of Artificial Intelligence Programming: Case Studies in "
  1365. "Common Lisp",
  1366. 1,
  1367. ),
  1368. ("Practical Django Projects", 1),
  1369. ("Python Web Development with Django", 3),
  1370. ("Sams Teach Yourself Django in 24 Hours", 1),
  1371. ("The Definitive Guide to Django: Web Development Done Right", 2),
  1372. ],
  1373. )
  1374. @skipUnlessDBFeature("allows_group_by_selected_pks")
  1375. def test_aggregate_unmanaged_model_columns(self):
  1376. """
  1377. Unmanaged models are sometimes used to represent database views which
  1378. may not allow grouping by selected primary key.
  1379. """
  1380. def assertQuerysetResults(queryset):
  1381. self.assertEqual(
  1382. [(b.name, b.num_authors) for b in queryset.order_by("name")],
  1383. [
  1384. ("Artificial Intelligence: A Modern Approach", 2),
  1385. (
  1386. "Paradigms of Artificial Intelligence Programming: Case "
  1387. "Studies in Common Lisp",
  1388. 1,
  1389. ),
  1390. ("Practical Django Projects", 1),
  1391. ("Python Web Development with Django", 3),
  1392. ("Sams Teach Yourself Django in 24 Hours", 1),
  1393. ("The Definitive Guide to Django: Web Development Done Right", 2),
  1394. ],
  1395. )
  1396. queryset = Book.objects.select_related("contact").annotate(
  1397. num_authors=Count("authors")
  1398. )
  1399. # Unmanaged origin model.
  1400. with mock.patch.object(Book._meta, "managed", False):
  1401. _, _, grouping = queryset.query.get_compiler(
  1402. using="default"
  1403. ).pre_sql_setup()
  1404. self.assertEqual(len(grouping), len(Book._meta.fields) + 1)
  1405. for index, field in enumerate(Book._meta.fields):
  1406. self.assertIn(field.name, grouping[index][0])
  1407. self.assertIn(Author._meta.pk.name, grouping[-1][0])
  1408. assertQuerysetResults(queryset)
  1409. # Unmanaged related model.
  1410. with mock.patch.object(Author._meta, "managed", False):
  1411. _, _, grouping = queryset.query.get_compiler(
  1412. using="default"
  1413. ).pre_sql_setup()
  1414. self.assertEqual(len(grouping), len(Author._meta.fields) + 1)
  1415. self.assertIn(Book._meta.pk.name, grouping[0][0])
  1416. for index, field in enumerate(Author._meta.fields):
  1417. self.assertIn(field.name, grouping[index + 1][0])
  1418. assertQuerysetResults(queryset)
  1419. @skipUnlessDBFeature("allows_group_by_selected_pks")
  1420. def test_aggregate_unmanaged_model_as_tables(self):
  1421. qs = Book.objects.select_related("contact").annotate(
  1422. num_authors=Count("authors")
  1423. )
  1424. # Force treating unmanaged models as tables.
  1425. with mock.patch(
  1426. "django.db.connection.features.allows_group_by_selected_pks_on_model",
  1427. return_value=True,
  1428. ):
  1429. with mock.patch.object(Book._meta, "managed", False), mock.patch.object(
  1430. Author._meta, "managed", False
  1431. ):
  1432. _, _, grouping = qs.query.get_compiler(using="default").pre_sql_setup()
  1433. self.assertEqual(len(grouping), 2)
  1434. self.assertIn("id", grouping[0][0])
  1435. self.assertIn("id", grouping[1][0])
  1436. self.assertQuerysetEqual(
  1437. qs.order_by("name"),
  1438. [
  1439. ("Artificial Intelligence: A Modern Approach", 2),
  1440. (
  1441. "Paradigms of Artificial Intelligence Programming: Case "
  1442. "Studies in Common Lisp",
  1443. 1,
  1444. ),
  1445. ("Practical Django Projects", 1),
  1446. ("Python Web Development with Django", 3),
  1447. ("Sams Teach Yourself Django in 24 Hours", 1),
  1448. (
  1449. "The Definitive Guide to Django: Web Development Done "
  1450. "Right",
  1451. 2,
  1452. ),
  1453. ],
  1454. attrgetter("name", "num_authors"),
  1455. )
  1456. def test_reverse_join_trimming(self):
  1457. qs = Author.objects.annotate(Count("book_contact_set__contact"))
  1458. self.assertIn(" JOIN ", str(qs.query))
  1459. def test_aggregation_with_generic_reverse_relation(self):
  1460. """
  1461. Regression test for #10870: Aggregates with joins ignore extra
  1462. filters provided by setup_joins
  1463. tests aggregations with generic reverse relations
  1464. """
  1465. django_book = Book.objects.get(name="Practical Django Projects")
  1466. ItemTag.objects.create(
  1467. object_id=django_book.id,
  1468. tag="intermediate",
  1469. content_type=ContentType.objects.get_for_model(django_book),
  1470. )
  1471. ItemTag.objects.create(
  1472. object_id=django_book.id,
  1473. tag="django",
  1474. content_type=ContentType.objects.get_for_model(django_book),
  1475. )
  1476. # Assign a tag to model with same PK as the book above. If the JOIN
  1477. # used in aggregation doesn't have content type as part of the
  1478. # condition the annotation will also count the 'hi mom' tag for b.
  1479. wmpk = WithManualPK.objects.create(id=django_book.pk)
  1480. ItemTag.objects.create(
  1481. object_id=wmpk.id,
  1482. tag="hi mom",
  1483. content_type=ContentType.objects.get_for_model(wmpk),
  1484. )
  1485. ai_book = Book.objects.get(
  1486. name__startswith="Paradigms of Artificial Intelligence"
  1487. )
  1488. ItemTag.objects.create(
  1489. object_id=ai_book.id,
  1490. tag="intermediate",
  1491. content_type=ContentType.objects.get_for_model(ai_book),
  1492. )
  1493. self.assertEqual(Book.objects.aggregate(Count("tags")), {"tags__count": 3})
  1494. results = Book.objects.annotate(Count("tags")).order_by("-tags__count", "name")
  1495. self.assertEqual(
  1496. [(b.name, b.tags__count) for b in results],
  1497. [
  1498. ("Practical Django Projects", 2),
  1499. (
  1500. "Paradigms of Artificial Intelligence Programming: Case Studies in "
  1501. "Common Lisp",
  1502. 1,
  1503. ),
  1504. ("Artificial Intelligence: A Modern Approach", 0),
  1505. ("Python Web Development with Django", 0),
  1506. ("Sams Teach Yourself Django in 24 Hours", 0),
  1507. ("The Definitive Guide to Django: Web Development Done Right", 0),
  1508. ],
  1509. )
  1510. def test_negated_aggregation(self):
  1511. expected_results = Author.objects.exclude(
  1512. pk__in=Author.objects.annotate(book_cnt=Count("book")).filter(book_cnt=2)
  1513. ).order_by("name")
  1514. expected_results = [a.name for a in expected_results]
  1515. qs = (
  1516. Author.objects.annotate(book_cnt=Count("book"))
  1517. .exclude(Q(book_cnt=2), Q(book_cnt=2))
  1518. .order_by("name")
  1519. )
  1520. self.assertQuerysetEqual(qs, expected_results, lambda b: b.name)
  1521. expected_results = Author.objects.exclude(
  1522. pk__in=Author.objects.annotate(book_cnt=Count("book")).filter(book_cnt=2)
  1523. ).order_by("name")
  1524. expected_results = [a.name for a in expected_results]
  1525. qs = (
  1526. Author.objects.annotate(book_cnt=Count("book"))
  1527. .exclude(Q(book_cnt=2) | Q(book_cnt=2))
  1528. .order_by("name")
  1529. )
  1530. self.assertQuerysetEqual(qs, expected_results, lambda b: b.name)
  1531. def test_name_filters(self):
  1532. qs = (
  1533. Author.objects.annotate(Count("book"))
  1534. .filter(Q(book__count__exact=2) | Q(name="Adrian Holovaty"))
  1535. .order_by("name")
  1536. )
  1537. self.assertQuerysetEqual(
  1538. qs, ["Adrian Holovaty", "Peter Norvig"], lambda b: b.name
  1539. )
  1540. def test_name_expressions(self):
  1541. # Aggregates are spotted correctly from F objects.
  1542. # Note that Adrian's age is 34 in the fixtures, and he has one book
  1543. # so both conditions match one author.
  1544. qs = (
  1545. Author.objects.annotate(Count("book"))
  1546. .filter(Q(name="Peter Norvig") | Q(age=F("book__count") + 33))
  1547. .order_by("name")
  1548. )
  1549. self.assertQuerysetEqual(
  1550. qs, ["Adrian Holovaty", "Peter Norvig"], lambda b: b.name
  1551. )
  1552. def test_filter_aggregates_or_connector(self):
  1553. q1 = Q(price__gt=50)
  1554. q2 = Q(authors__count__gt=1)
  1555. query = Book.objects.annotate(Count("authors")).filter(q1 | q2).order_by("pk")
  1556. self.assertQuerysetEqual(
  1557. query,
  1558. [self.b1.pk, self.b4.pk, self.b5.pk, self.b6.pk],
  1559. attrgetter("pk"),
  1560. )
  1561. def test_filter_aggregates_negated_and_connector(self):
  1562. q1 = Q(price__gt=50)
  1563. q2 = Q(authors__count__gt=1)
  1564. query = (
  1565. Book.objects.annotate(Count("authors")).filter(~(q1 & q2)).order_by("pk")
  1566. )
  1567. self.assertQuerysetEqual(
  1568. query,
  1569. [self.b1.pk, self.b2.pk, self.b3.pk, self.b4.pk, self.b6.pk],
  1570. attrgetter("pk"),
  1571. )
  1572. def test_filter_aggregates_xor_connector(self):
  1573. q1 = Q(price__gt=50)
  1574. q2 = Q(authors__count__gt=1)
  1575. query = Book.objects.annotate(Count("authors")).filter(q1 ^ q2).order_by("pk")
  1576. self.assertQuerysetEqual(
  1577. query,
  1578. [self.b1.pk, self.b4.pk, self.b6.pk],
  1579. attrgetter("pk"),
  1580. )
  1581. def test_filter_aggregates_negated_xor_connector(self):
  1582. q1 = Q(price__gt=50)
  1583. q2 = Q(authors__count__gt=1)
  1584. query = (
  1585. Book.objects.annotate(Count("authors")).filter(~(q1 ^ q2)).order_by("pk")
  1586. )
  1587. self.assertQuerysetEqual(
  1588. query,
  1589. [self.b2.pk, self.b3.pk, self.b5.pk],
  1590. attrgetter("pk"),
  1591. )
  1592. def test_ticket_11293_q_immutable(self):
  1593. """
  1594. Splitting a q object to parts for where/having doesn't alter
  1595. the original q-object.
  1596. """
  1597. q1 = Q(isbn="")
  1598. q2 = Q(authors__count__gt=1)
  1599. query = Book.objects.annotate(Count("authors"))
  1600. query.filter(q1 | q2)
  1601. self.assertEqual(len(q2.children), 1)
  1602. def test_fobj_group_by(self):
  1603. """
  1604. An F() object referring to related column works correctly in group by.
  1605. """
  1606. qs = Book.objects.annotate(account=Count("authors")).filter(
  1607. account=F("publisher__num_awards")
  1608. )
  1609. self.assertQuerysetEqual(
  1610. qs, ["Sams Teach Yourself Django in 24 Hours"], lambda b: b.name
  1611. )
  1612. def test_annotate_reserved_word(self):
  1613. """
  1614. Regression #18333 - Ensure annotated column name is properly quoted.
  1615. """
  1616. vals = Book.objects.annotate(select=Count("authors__id")).aggregate(
  1617. Sum("select"), Avg("select")
  1618. )
  1619. self.assertEqual(
  1620. vals,
  1621. {
  1622. "select__sum": 10,
  1623. "select__avg": Approximate(1.666, places=2),
  1624. },
  1625. )
  1626. def test_annotate_on_relation(self):
  1627. book = Book.objects.annotate(
  1628. avg_price=Avg("price"), publisher_name=F("publisher__name")
  1629. ).get(pk=self.b1.pk)
  1630. self.assertEqual(book.avg_price, 30.00)
  1631. self.assertEqual(book.publisher_name, "Apress")
  1632. def test_aggregate_on_relation(self):
  1633. # A query with an existing annotation aggregation on a relation should
  1634. # succeed.
  1635. qs = Book.objects.annotate(avg_price=Avg("price")).aggregate(
  1636. publisher_awards=Sum("publisher__num_awards")
  1637. )
  1638. self.assertEqual(qs["publisher_awards"], 30)
  1639. def test_annotate_distinct_aggregate(self):
  1640. # There are three books with rating of 4.0 and two of the books have
  1641. # the same price. Hence, the distinct removes one rating of 4.0
  1642. # from the results.
  1643. vals1 = (
  1644. Book.objects.values("rating", "price")
  1645. .distinct()
  1646. .aggregate(result=Sum("rating"))
  1647. )
  1648. vals2 = Book.objects.aggregate(result=Sum("rating") - Value(4.0))
  1649. self.assertEqual(vals1, vals2)
  1650. def test_annotate_values_list_flat(self):
  1651. """Find ages that are shared by at least two authors."""
  1652. qs = (
  1653. Author.objects.values_list("age", flat=True)
  1654. .annotate(age_count=Count("age"))
  1655. .filter(age_count__gt=1)
  1656. )
  1657. self.assertSequenceEqual(qs, [29])
  1658. def test_allow_distinct(self):
  1659. class MyAggregate(Aggregate):
  1660. pass
  1661. with self.assertRaisesMessage(TypeError, "MyAggregate does not allow distinct"):
  1662. MyAggregate("foo", distinct=True)
  1663. class DistinctAggregate(Aggregate):
  1664. allow_distinct = True
  1665. DistinctAggregate("foo", distinct=True)
  1666. @skipUnlessDBFeature("supports_subqueries_in_group_by")
  1667. def test_having_subquery_select(self):
  1668. authors = Author.objects.filter(pk=self.a1.pk)
  1669. books = Book.objects.annotate(Count("authors")).filter(
  1670. Q(authors__in=authors) | Q(authors__count__gt=2)
  1671. )
  1672. self.assertEqual(set(books), {self.b1, self.b4})
  1673. class JoinPromotionTests(TestCase):
  1674. def test_ticket_21150(self):
  1675. b = Bravo.objects.create()
  1676. c = Charlie.objects.create(bravo=b)
  1677. qs = Charlie.objects.select_related("alfa").annotate(Count("bravo__charlie"))
  1678. self.assertSequenceEqual(qs, [c])
  1679. self.assertIs(qs[0].alfa, None)
  1680. a = Alfa.objects.create()
  1681. c.alfa = a
  1682. c.save()
  1683. # Force re-evaluation
  1684. qs = qs.all()
  1685. self.assertSequenceEqual(qs, [c])
  1686. self.assertEqual(qs[0].alfa, a)
  1687. def test_existing_join_not_promoted(self):
  1688. # No promotion for existing joins
  1689. qs = Charlie.objects.filter(alfa__name__isnull=False).annotate(
  1690. Count("alfa__name")
  1691. )
  1692. self.assertIn(" INNER JOIN ", str(qs.query))
  1693. # Also, the existing join is unpromoted when doing filtering for already
  1694. # promoted join.
  1695. qs = Charlie.objects.annotate(Count("alfa__name")).filter(
  1696. alfa__name__isnull=False
  1697. )
  1698. self.assertIn(" INNER JOIN ", str(qs.query))
  1699. # But, as the join is nullable first use by annotate will be LOUTER
  1700. qs = Charlie.objects.annotate(Count("alfa__name"))
  1701. self.assertIn(" LEFT OUTER JOIN ", str(qs.query))
  1702. def test_non_nullable_fk_not_promoted(self):
  1703. qs = Book.objects.annotate(Count("contact__name"))
  1704. self.assertIn(" INNER JOIN ", str(qs.query))
  1705. class SelfReferentialFKTests(TestCase):
  1706. def test_ticket_24748(self):
  1707. t1 = SelfRefFK.objects.create(name="t1")
  1708. SelfRefFK.objects.create(name="t2", parent=t1)
  1709. SelfRefFK.objects.create(name="t3", parent=t1)
  1710. self.assertQuerysetEqual(
  1711. SelfRefFK.objects.annotate(num_children=Count("children")).order_by("name"),
  1712. [("t1", 2), ("t2", 0), ("t3", 0)],
  1713. lambda x: (x.name, x.num_children),
  1714. )