tests.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. from datetime import date
  2. from decimal import Decimal
  3. from unittest import mock
  4. from django.db import connection, transaction
  5. from django.db.models import (
  6. BooleanField,
  7. Case,
  8. Count,
  9. DecimalField,
  10. ExpressionWrapper,
  11. F,
  12. FilteredRelation,
  13. Q,
  14. Sum,
  15. Value,
  16. When,
  17. )
  18. from django.db.models.functions import Concat
  19. from django.db.models.lookups import Exact, IStartsWith
  20. from django.test import TestCase
  21. from django.test.testcases import skipUnlessDBFeature
  22. from .models import (
  23. Author,
  24. Book,
  25. BookDailySales,
  26. Borrower,
  27. Currency,
  28. Editor,
  29. ExchangeRate,
  30. RentalSession,
  31. Reservation,
  32. Seller,
  33. )
  34. class FilteredRelationTests(TestCase):
  35. @classmethod
  36. def setUpTestData(cls):
  37. cls.author1 = Author.objects.create(name="Alice")
  38. cls.author2 = Author.objects.create(name="Jane")
  39. cls.editor_a = Editor.objects.create(name="a")
  40. cls.editor_b = Editor.objects.create(name="b")
  41. cls.book1 = Book.objects.create(
  42. title="Poem by Alice",
  43. editor=cls.editor_a,
  44. author=cls.author1,
  45. )
  46. cls.book1.generic_author.set([cls.author2])
  47. cls.book2 = Book.objects.create(
  48. title="The book by Jane A",
  49. editor=cls.editor_b,
  50. author=cls.author2,
  51. )
  52. cls.book3 = Book.objects.create(
  53. title="The book by Jane B",
  54. editor=cls.editor_b,
  55. author=cls.author2,
  56. )
  57. cls.book4 = Book.objects.create(
  58. title="The book by Alice",
  59. editor=cls.editor_a,
  60. author=cls.author1,
  61. )
  62. cls.author1.favorite_books.add(cls.book2)
  63. cls.author1.favorite_books.add(cls.book3)
  64. def test_select_related(self):
  65. qs = (
  66. Author.objects.annotate(
  67. book_join=FilteredRelation("book"),
  68. )
  69. .select_related("book_join__editor")
  70. .order_by("pk", "book_join__pk")
  71. )
  72. with self.assertNumQueries(1):
  73. self.assertQuerySetEqual(
  74. qs,
  75. [
  76. (self.author1, self.book1, self.editor_a, self.author1),
  77. (self.author1, self.book4, self.editor_a, self.author1),
  78. (self.author2, self.book2, self.editor_b, self.author2),
  79. (self.author2, self.book3, self.editor_b, self.author2),
  80. ],
  81. lambda x: (x, x.book_join, x.book_join.editor, x.book_join.author),
  82. )
  83. def test_select_related_multiple(self):
  84. qs = (
  85. Book.objects.annotate(
  86. author_join=FilteredRelation("author"),
  87. editor_join=FilteredRelation("editor"),
  88. )
  89. .select_related("author_join", "editor_join")
  90. .order_by("pk")
  91. )
  92. self.assertQuerySetEqual(
  93. qs,
  94. [
  95. (self.book1, self.author1, self.editor_a),
  96. (self.book2, self.author2, self.editor_b),
  97. (self.book3, self.author2, self.editor_b),
  98. (self.book4, self.author1, self.editor_a),
  99. ],
  100. lambda x: (x, x.author_join, x.editor_join),
  101. )
  102. def test_select_related_with_empty_relation(self):
  103. qs = (
  104. Author.objects.annotate(
  105. book_join=FilteredRelation("book", condition=Q(pk=-1)),
  106. )
  107. .select_related("book_join")
  108. .order_by("pk")
  109. )
  110. self.assertSequenceEqual(qs, [self.author1, self.author2])
  111. def test_select_related_foreign_key(self):
  112. qs = (
  113. Book.objects.annotate(
  114. author_join=FilteredRelation("author"),
  115. )
  116. .select_related("author_join")
  117. .order_by("pk")
  118. )
  119. with self.assertNumQueries(1):
  120. self.assertQuerySetEqual(
  121. qs,
  122. [
  123. (self.book1, self.author1),
  124. (self.book2, self.author2),
  125. (self.book3, self.author2),
  126. (self.book4, self.author1),
  127. ],
  128. lambda x: (x, x.author_join),
  129. )
  130. @skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of")
  131. def test_select_related_foreign_key_for_update_of(self):
  132. with transaction.atomic():
  133. qs = (
  134. Book.objects.annotate(
  135. author_join=FilteredRelation("author"),
  136. )
  137. .select_related("author_join")
  138. .select_for_update(of=("self",))
  139. .order_by("pk")
  140. )
  141. with self.assertNumQueries(1):
  142. self.assertQuerySetEqual(
  143. qs,
  144. [
  145. (self.book1, self.author1),
  146. (self.book2, self.author2),
  147. (self.book3, self.author2),
  148. (self.book4, self.author1),
  149. ],
  150. lambda x: (x, x.author_join),
  151. )
  152. def test_without_join(self):
  153. self.assertCountEqual(
  154. Author.objects.annotate(
  155. book_alice=FilteredRelation(
  156. "book", condition=Q(book__title__iexact="poem by alice")
  157. ),
  158. ),
  159. [self.author1, self.author2],
  160. )
  161. def test_with_join(self):
  162. self.assertSequenceEqual(
  163. Author.objects.annotate(
  164. book_alice=FilteredRelation(
  165. "book", condition=Q(book__title__iexact="poem by alice")
  166. ),
  167. ).filter(book_alice__isnull=False),
  168. [self.author1],
  169. )
  170. def test_with_exclude(self):
  171. self.assertSequenceEqual(
  172. Author.objects.annotate(
  173. book_alice=FilteredRelation(
  174. "book", condition=Q(book__title__iexact="poem by alice")
  175. ),
  176. ).exclude(book_alice__isnull=False),
  177. [self.author2],
  178. )
  179. def test_with_join_and_complex_condition(self):
  180. self.assertSequenceEqual(
  181. Author.objects.annotate(
  182. book_alice=FilteredRelation(
  183. "book",
  184. condition=Q(
  185. Q(book__title__iexact="poem by alice")
  186. | Q(book__state=Book.RENTED)
  187. ),
  188. ),
  189. ).filter(book_alice__isnull=False),
  190. [self.author1],
  191. )
  192. def test_internal_queryset_alias_mapping(self):
  193. queryset = Author.objects.annotate(
  194. book_alice=FilteredRelation(
  195. "book", condition=Q(book__title__iexact="poem by alice")
  196. ),
  197. ).filter(book_alice__isnull=False)
  198. self.assertIn(
  199. "INNER JOIN {} book_alice ON".format(
  200. connection.ops.quote_name("filtered_relation_book")
  201. ),
  202. str(queryset.query),
  203. )
  204. def test_multiple(self):
  205. qs = (
  206. Author.objects.annotate(
  207. book_title_alice=FilteredRelation(
  208. "book", condition=Q(book__title__contains="Alice")
  209. ),
  210. book_title_jane=FilteredRelation(
  211. "book", condition=Q(book__title__icontains="Jane")
  212. ),
  213. )
  214. .filter(name="Jane")
  215. .values("book_title_alice__title", "book_title_jane__title")
  216. )
  217. empty = "" if connection.features.interprets_empty_strings_as_nulls else None
  218. self.assertCountEqual(
  219. qs,
  220. [
  221. {
  222. "book_title_alice__title": empty,
  223. "book_title_jane__title": "The book by Jane A",
  224. },
  225. {
  226. "book_title_alice__title": empty,
  227. "book_title_jane__title": "The book by Jane B",
  228. },
  229. ],
  230. )
  231. def test_with_multiple_filter(self):
  232. self.assertSequenceEqual(
  233. Author.objects.annotate(
  234. book_editor_a=FilteredRelation(
  235. "book",
  236. condition=Q(
  237. book__title__icontains="book", book__editor_id=self.editor_a.pk
  238. ),
  239. ),
  240. ).filter(book_editor_a__isnull=False),
  241. [self.author1],
  242. )
  243. def test_multiple_times(self):
  244. self.assertSequenceEqual(
  245. Author.objects.annotate(
  246. book_title_alice=FilteredRelation(
  247. "book", condition=Q(book__title__icontains="alice")
  248. ),
  249. )
  250. .filter(book_title_alice__isnull=False)
  251. .filter(book_title_alice__isnull=False)
  252. .distinct(),
  253. [self.author1],
  254. )
  255. def test_exclude_relation_with_join(self):
  256. self.assertSequenceEqual(
  257. Author.objects.annotate(
  258. book_alice=FilteredRelation(
  259. "book", condition=~Q(book__title__icontains="alice")
  260. ),
  261. )
  262. .filter(book_alice__isnull=False)
  263. .distinct(),
  264. [self.author2],
  265. )
  266. def test_with_m2m(self):
  267. qs = Author.objects.annotate(
  268. favorite_books_written_by_jane=FilteredRelation(
  269. "favorite_books",
  270. condition=Q(favorite_books__in=[self.book2]),
  271. ),
  272. ).filter(favorite_books_written_by_jane__isnull=False)
  273. self.assertSequenceEqual(qs, [self.author1])
  274. def test_with_m2m_deep(self):
  275. qs = Author.objects.annotate(
  276. favorite_books_written_by_jane=FilteredRelation(
  277. "favorite_books",
  278. condition=Q(favorite_books__author=self.author2),
  279. ),
  280. ).filter(favorite_books_written_by_jane__title="The book by Jane B")
  281. self.assertSequenceEqual(qs, [self.author1])
  282. def test_with_m2m_multijoin(self):
  283. qs = (
  284. Author.objects.annotate(
  285. favorite_books_written_by_jane=FilteredRelation(
  286. "favorite_books",
  287. condition=Q(favorite_books__author=self.author2),
  288. )
  289. )
  290. .filter(favorite_books_written_by_jane__editor__name="b")
  291. .distinct()
  292. )
  293. self.assertSequenceEqual(qs, [self.author1])
  294. def test_values_list(self):
  295. self.assertSequenceEqual(
  296. Author.objects.annotate(
  297. book_alice=FilteredRelation(
  298. "book", condition=Q(book__title__iexact="poem by alice")
  299. ),
  300. )
  301. .filter(book_alice__isnull=False)
  302. .values_list("book_alice__title", flat=True),
  303. ["Poem by Alice"],
  304. )
  305. def test_values(self):
  306. self.assertSequenceEqual(
  307. Author.objects.annotate(
  308. book_alice=FilteredRelation(
  309. "book", condition=Q(book__title__iexact="poem by alice")
  310. ),
  311. )
  312. .filter(book_alice__isnull=False)
  313. .values(),
  314. [
  315. {
  316. "id": self.author1.pk,
  317. "name": "Alice",
  318. "content_type_id": None,
  319. "object_id": None,
  320. }
  321. ],
  322. )
  323. def test_extra(self):
  324. self.assertSequenceEqual(
  325. Author.objects.annotate(
  326. book_alice=FilteredRelation(
  327. "book", condition=Q(book__title__iexact="poem by alice")
  328. ),
  329. )
  330. .filter(book_alice__isnull=False)
  331. .extra(where=["1 = 1"]),
  332. [self.author1],
  333. )
  334. @skipUnlessDBFeature("supports_select_union")
  335. def test_union(self):
  336. qs1 = Author.objects.annotate(
  337. book_alice=FilteredRelation(
  338. "book", condition=Q(book__title__iexact="poem by alice")
  339. ),
  340. ).filter(book_alice__isnull=False)
  341. qs2 = Author.objects.annotate(
  342. book_jane=FilteredRelation(
  343. "book", condition=Q(book__title__iexact="the book by jane a")
  344. ),
  345. ).filter(book_jane__isnull=False)
  346. self.assertSequenceEqual(qs1.union(qs2), [self.author1, self.author2])
  347. @skipUnlessDBFeature("supports_select_intersection")
  348. def test_intersection(self):
  349. qs1 = Author.objects.annotate(
  350. book_alice=FilteredRelation(
  351. "book", condition=Q(book__title__iexact="poem by alice")
  352. ),
  353. ).filter(book_alice__isnull=False)
  354. qs2 = Author.objects.annotate(
  355. book_jane=FilteredRelation(
  356. "book", condition=Q(book__title__iexact="the book by jane a")
  357. ),
  358. ).filter(book_jane__isnull=False)
  359. self.assertSequenceEqual(qs1.intersection(qs2), [])
  360. @skipUnlessDBFeature("supports_select_difference")
  361. def test_difference(self):
  362. qs1 = Author.objects.annotate(
  363. book_alice=FilteredRelation(
  364. "book", condition=Q(book__title__iexact="poem by alice")
  365. ),
  366. ).filter(book_alice__isnull=False)
  367. qs2 = Author.objects.annotate(
  368. book_jane=FilteredRelation(
  369. "book", condition=Q(book__title__iexact="the book by jane a")
  370. ),
  371. ).filter(book_jane__isnull=False)
  372. self.assertSequenceEqual(qs1.difference(qs2), [self.author1])
  373. def test_select_for_update(self):
  374. self.assertSequenceEqual(
  375. Author.objects.annotate(
  376. book_jane=FilteredRelation(
  377. "book", condition=Q(book__title__iexact="the book by jane a")
  378. ),
  379. )
  380. .filter(book_jane__isnull=False)
  381. .select_for_update(),
  382. [self.author2],
  383. )
  384. def test_defer(self):
  385. # One query for the list and one query for the deferred title.
  386. with self.assertNumQueries(2):
  387. self.assertQuerySetEqual(
  388. Author.objects.annotate(
  389. book_alice=FilteredRelation(
  390. "book", condition=Q(book__title__iexact="poem by alice")
  391. ),
  392. )
  393. .filter(book_alice__isnull=False)
  394. .select_related("book_alice")
  395. .defer("book_alice__title"),
  396. ["Poem by Alice"],
  397. lambda author: author.book_alice.title,
  398. )
  399. def test_only_not_supported(self):
  400. msg = "only() is not supported with FilteredRelation."
  401. with self.assertRaisesMessage(ValueError, msg):
  402. Author.objects.annotate(
  403. book_alice=FilteredRelation(
  404. "book", condition=Q(book__title__iexact="poem by alice")
  405. ),
  406. ).filter(book_alice__isnull=False).select_related("book_alice").only(
  407. "book_alice__state"
  408. )
  409. def test_as_subquery(self):
  410. inner_qs = Author.objects.annotate(
  411. book_alice=FilteredRelation(
  412. "book", condition=Q(book__title__iexact="poem by alice")
  413. ),
  414. ).filter(book_alice__isnull=False)
  415. qs = Author.objects.filter(id__in=inner_qs)
  416. self.assertSequenceEqual(qs, [self.author1])
  417. def test_nested_foreign_key(self):
  418. qs = (
  419. Author.objects.annotate(
  420. book_editor_worked_with=FilteredRelation(
  421. "book__editor",
  422. condition=Q(book__title__icontains="book by"),
  423. ),
  424. )
  425. .filter(
  426. book_editor_worked_with__isnull=False,
  427. )
  428. .select_related(
  429. "book_editor_worked_with",
  430. )
  431. .order_by("pk", "book_editor_worked_with__pk")
  432. )
  433. with self.assertNumQueries(1):
  434. self.assertQuerySetEqual(
  435. qs,
  436. [
  437. (self.author1, self.editor_a),
  438. (self.author2, self.editor_b),
  439. (self.author2, self.editor_b),
  440. ],
  441. lambda x: (x, x.book_editor_worked_with),
  442. )
  443. def test_nested_foreign_key_nested_field(self):
  444. qs = (
  445. Author.objects.annotate(
  446. book_editor_worked_with=FilteredRelation(
  447. "book__editor", condition=Q(book__title__icontains="book by")
  448. ),
  449. )
  450. .filter(
  451. book_editor_worked_with__isnull=False,
  452. )
  453. .values(
  454. "name",
  455. "book_editor_worked_with__name",
  456. )
  457. .order_by("name", "book_editor_worked_with__name")
  458. .distinct()
  459. )
  460. self.assertSequenceEqual(
  461. qs,
  462. [
  463. {
  464. "name": self.author1.name,
  465. "book_editor_worked_with__name": self.editor_a.name,
  466. },
  467. {
  468. "name": self.author2.name,
  469. "book_editor_worked_with__name": self.editor_b.name,
  470. },
  471. ],
  472. )
  473. def test_nested_foreign_key_filtered_base_object(self):
  474. qs = (
  475. Author.objects.annotate(
  476. alice_editors=FilteredRelation(
  477. "book__editor",
  478. condition=Q(name="Alice"),
  479. ),
  480. )
  481. .values(
  482. "name",
  483. "alice_editors__pk",
  484. )
  485. .order_by("name", "alice_editors__name")
  486. .distinct()
  487. )
  488. self.assertSequenceEqual(
  489. qs,
  490. [
  491. {"name": self.author1.name, "alice_editors__pk": self.editor_a.pk},
  492. {"name": self.author2.name, "alice_editors__pk": None},
  493. ],
  494. )
  495. def test_nested_m2m_filtered(self):
  496. qs = (
  497. Book.objects.annotate(
  498. favorite_book=FilteredRelation(
  499. "author__favorite_books",
  500. condition=Q(author__favorite_books__title__icontains="book by"),
  501. ),
  502. )
  503. .values(
  504. "title",
  505. "favorite_book__pk",
  506. )
  507. .order_by("title", "favorite_book__title")
  508. )
  509. self.assertSequenceEqual(
  510. qs,
  511. [
  512. {"title": self.book1.title, "favorite_book__pk": self.book2.pk},
  513. {"title": self.book1.title, "favorite_book__pk": self.book3.pk},
  514. {"title": self.book4.title, "favorite_book__pk": self.book2.pk},
  515. {"title": self.book4.title, "favorite_book__pk": self.book3.pk},
  516. {"title": self.book2.title, "favorite_book__pk": None},
  517. {"title": self.book3.title, "favorite_book__pk": None},
  518. ],
  519. )
  520. def test_nested_chained_relations(self):
  521. qs = (
  522. Author.objects.annotate(
  523. my_books=FilteredRelation(
  524. "book",
  525. condition=Q(book__title__icontains="book by"),
  526. ),
  527. preferred_by_authors=FilteredRelation(
  528. "my_books__preferred_by_authors",
  529. condition=Q(my_books__preferred_by_authors__name="Alice"),
  530. ),
  531. )
  532. .annotate(
  533. author=F("name"),
  534. book_title=F("my_books__title"),
  535. preferred_by_author_pk=F("preferred_by_authors"),
  536. )
  537. .order_by("author", "book_title", "preferred_by_author_pk")
  538. )
  539. self.assertQuerySetEqual(
  540. qs,
  541. [
  542. ("Alice", "The book by Alice", None),
  543. ("Jane", "The book by Jane A", self.author1.pk),
  544. ("Jane", "The book by Jane B", self.author1.pk),
  545. ],
  546. lambda x: (x.author, x.book_title, x.preferred_by_author_pk),
  547. )
  548. def test_three_level_nested_chained_relations(self):
  549. borrower = Borrower.objects.create(name="Jenny")
  550. Reservation.objects.create(
  551. borrower=borrower,
  552. book=self.book1,
  553. state=Reservation.STOPPED,
  554. )
  555. qs = Author.objects.annotate(
  556. my_books=FilteredRelation("book"),
  557. my_reserved_books=FilteredRelation(
  558. "my_books__reservation",
  559. condition=Q(my_books__reservation__state=Reservation.STOPPED),
  560. ),
  561. my_readers=FilteredRelation(
  562. "my_reserved_books__borrower",
  563. condition=Q(my_reserved_books__borrower=borrower),
  564. ),
  565. )
  566. self.assertSequenceEqual(
  567. qs.filter(my_readers=borrower).values_list("name", flat=True), ["Alice"]
  568. )
  569. def test_deep_nested_foreign_key(self):
  570. qs = (
  571. Book.objects.annotate(
  572. author_favorite_book_editor=FilteredRelation(
  573. "author__favorite_books__editor",
  574. condition=Q(author__favorite_books__title__icontains="Jane A"),
  575. ),
  576. )
  577. .filter(
  578. author_favorite_book_editor__isnull=False,
  579. )
  580. .select_related(
  581. "author_favorite_book_editor",
  582. )
  583. .order_by("pk", "author_favorite_book_editor__pk")
  584. )
  585. with self.assertNumQueries(1):
  586. self.assertQuerySetEqual(
  587. qs,
  588. [
  589. (self.book1, self.editor_b),
  590. (self.book4, self.editor_b),
  591. ],
  592. lambda x: (x, x.author_favorite_book_editor),
  593. )
  594. def test_relation_name_lookup(self):
  595. msg = (
  596. "FilteredRelation's relation_name cannot contain lookups (got "
  597. "'book__title__icontains')."
  598. )
  599. with self.assertRaisesMessage(ValueError, msg):
  600. Author.objects.annotate(
  601. book_title=FilteredRelation(
  602. "book__title__icontains",
  603. condition=Q(book__title="Poem by Alice"),
  604. ),
  605. )
  606. def test_condition_outside_relation_name(self):
  607. msg = (
  608. "FilteredRelation's condition doesn't support relations outside "
  609. "the 'book__editor' (got 'book__author__name__icontains')."
  610. )
  611. with self.assertRaisesMessage(ValueError, msg):
  612. Author.objects.annotate(
  613. book_editor=FilteredRelation(
  614. "book__editor",
  615. condition=Q(book__author__name__icontains="book"),
  616. ),
  617. )
  618. def test_condition_with_exact_lookup_outside_relation_name(self):
  619. qs = Author.objects.annotate(
  620. book_editor=FilteredRelation(
  621. "book__editor",
  622. condition=Q(book__author__name="book"),
  623. ),
  624. ).filter(book_editor__isnull=True)
  625. self.assertEqual(qs.count(), 4)
  626. def test_condition_with_func_and_lookup_outside_relation_name(self):
  627. qs = Author.objects.annotate(
  628. book_editor=FilteredRelation(
  629. "book__editor",
  630. condition=Q(
  631. book__title=Concat(Value("The book by "), F("book__author__name"))
  632. ),
  633. ),
  634. ).filter(book_editor__isnull=False)
  635. self.assertEqual(qs.count(), 1)
  636. def test_condition_deeper_relation_name(self):
  637. msg = (
  638. "FilteredRelation's condition doesn't support nested relations "
  639. "deeper than the relation_name (got "
  640. "'book__editor__name__icontains' for 'book')."
  641. )
  642. with self.assertRaisesMessage(ValueError, msg):
  643. Author.objects.annotate(
  644. book_editor=FilteredRelation(
  645. "book",
  646. condition=Q(book__editor__name__icontains="b"),
  647. ),
  648. )
  649. def test_condition_deeper_relation_name_implicit_exact(self):
  650. msg = (
  651. "FilteredRelation's condition doesn't support nested relations "
  652. "deeper than the relation_name (got 'book__editor__name' for 'book')."
  653. )
  654. with self.assertRaisesMessage(ValueError, msg):
  655. Author.objects.annotate(
  656. book_editor=FilteredRelation(
  657. "book",
  658. condition=Q(book__editor__name="b"),
  659. ),
  660. )
  661. def test_with_empty_relation_name_error(self):
  662. with self.assertRaisesMessage(ValueError, "relation_name cannot be empty."):
  663. FilteredRelation("", condition=Q(blank=""))
  664. def test_with_condition_as_expression_error(self):
  665. msg = "condition argument must be a Q() instance."
  666. expression = Case(
  667. When(book__title__iexact="poem by alice", then=True),
  668. default=False,
  669. )
  670. with self.assertRaisesMessage(ValueError, msg):
  671. FilteredRelation("book", condition=expression)
  672. def test_with_prefetch_related(self):
  673. msg = "prefetch_related() is not supported with FilteredRelation."
  674. qs = Author.objects.annotate(
  675. book_title_contains_b=FilteredRelation(
  676. "book", condition=Q(book__title__icontains="b")
  677. ),
  678. ).filter(
  679. book_title_contains_b__isnull=False,
  680. )
  681. with self.assertRaisesMessage(ValueError, msg):
  682. qs.prefetch_related("book_title_contains_b")
  683. with self.assertRaisesMessage(ValueError, msg):
  684. qs.prefetch_related("book_title_contains_b__editor")
  685. def test_with_generic_foreign_key(self):
  686. self.assertSequenceEqual(
  687. Book.objects.annotate(
  688. generic_authored_book=FilteredRelation(
  689. "generic_author", condition=Q(generic_author__isnull=False)
  690. ),
  691. ).filter(generic_authored_book__isnull=False),
  692. [self.book1],
  693. )
  694. def test_eq(self):
  695. self.assertEqual(
  696. FilteredRelation("book", condition=Q(book__title="b")), mock.ANY
  697. )
  698. def test_conditional_expression(self):
  699. qs = Author.objects.annotate(
  700. the_book=FilteredRelation("book", condition=Q(Value(False))),
  701. ).filter(the_book__isnull=False)
  702. self.assertSequenceEqual(qs, [])
  703. def test_expression_outside_relation_name(self):
  704. qs = Author.objects.annotate(
  705. book_editor=FilteredRelation(
  706. "book__editor",
  707. condition=Q(
  708. Exact(F("book__author__name"), "Alice"),
  709. Value(True),
  710. book__title__startswith="Poem",
  711. ),
  712. ),
  713. ).filter(book_editor__isnull=False)
  714. self.assertSequenceEqual(qs, [self.author1])
  715. def test_conditional_expression_with_case(self):
  716. qs = Book.objects.annotate(
  717. alice_author=FilteredRelation(
  718. "author",
  719. condition=Q(
  720. Case(When(author__name="Alice", then=True), default=False),
  721. ),
  722. ),
  723. ).filter(alice_author__isnull=False)
  724. self.assertCountEqual(qs, [self.book1, self.book4])
  725. def test_conditional_expression_outside_relation_name(self):
  726. tests = [
  727. Q(Case(When(book__author__name="Alice", then=True), default=False)),
  728. Q(
  729. ExpressionWrapper(
  730. Q(Value(True), Exact(F("book__author__name"), "Alice")),
  731. output_field=BooleanField(),
  732. ),
  733. ),
  734. ]
  735. for condition in tests:
  736. with self.subTest(condition=condition):
  737. qs = Author.objects.annotate(
  738. book_editor=FilteredRelation("book__editor", condition=condition),
  739. ).filter(book_editor__isnull=True)
  740. self.assertSequenceEqual(qs, [self.author2, self.author2])
  741. def test_conditional_expression_with_lookup(self):
  742. lookups = [
  743. Q(book__title__istartswith="poem"),
  744. Q(IStartsWith(F("book__title"), "poem")),
  745. ]
  746. for condition in lookups:
  747. with self.subTest(condition=condition):
  748. qs = Author.objects.annotate(
  749. poem_book=FilteredRelation("book", condition=condition)
  750. ).filter(poem_book__isnull=False)
  751. self.assertSequenceEqual(qs, [self.author1])
  752. def test_conditional_expression_with_expressionwrapper(self):
  753. qs = Author.objects.annotate(
  754. poem_book=FilteredRelation(
  755. "book",
  756. condition=Q(
  757. ExpressionWrapper(
  758. Q(Exact(F("book__title"), "Poem by Alice")),
  759. output_field=BooleanField(),
  760. ),
  761. ),
  762. ),
  763. ).filter(poem_book__isnull=False)
  764. self.assertSequenceEqual(qs, [self.author1])
  765. def test_conditional_expression_with_multiple_fields(self):
  766. qs = Author.objects.annotate(
  767. my_books=FilteredRelation(
  768. "book__author",
  769. condition=Q(Exact(F("book__author__name"), F("book__author__name"))),
  770. ),
  771. ).filter(my_books__isnull=True)
  772. self.assertSequenceEqual(qs, [])
  773. def test_conditional_expression_rhs_contains_relation_name(self):
  774. qs = Book.objects.annotate(
  775. rel=FilteredRelation(
  776. "editor",
  777. condition=Q(id=1 * F("number_editor")),
  778. )
  779. ).filter(rel__isnull=True)
  780. self.assertSequenceEqual(qs, [])
  781. def test_conditional_expression_rhs_startswith_relation_name(self):
  782. qs = Book.objects.annotate(
  783. rel=FilteredRelation(
  784. "editor",
  785. condition=Q(id=1 * F("editor_number")),
  786. )
  787. ).filter(rel__isnull=True)
  788. self.assertSequenceEqual(qs, [])
  789. def test_conditional_expression_lhs_startswith_relation_name(self):
  790. qs = Book.objects.annotate(
  791. rel=FilteredRelation(
  792. "editor",
  793. condition=Q(editor_number__gt=1),
  794. )
  795. ).filter(rel__isnull=True)
  796. self.assertSequenceEqual(qs, [])
  797. def test_conditional_expression_lhs_contains_relation_name(self):
  798. qs = Book.objects.annotate(
  799. rel=FilteredRelation(
  800. "editor",
  801. condition=Q(number_editor__gt=1),
  802. )
  803. ).filter(rel__isnull=True)
  804. self.assertSequenceEqual(qs, [])
  805. def test_conditional_expression_does_not_support_queryset(self):
  806. msg = "Passing a QuerySet within a FilteredRelation is not supported."
  807. with self.assertRaisesMessage(ValueError, msg):
  808. Author.objects.annotate(
  809. poem_book=FilteredRelation(
  810. "book",
  811. condition=Q(book__in=Book.objects.filter(title__istartswith="a")),
  812. ),
  813. ).filter(poem_book__isnull=False)
  814. class FilteredRelationAggregationTests(TestCase):
  815. @classmethod
  816. def setUpTestData(cls):
  817. cls.author1 = Author.objects.create(name="Alice")
  818. cls.editor_a = Editor.objects.create(name="a")
  819. cls.book1 = Book.objects.create(
  820. title="Poem by Alice",
  821. editor=cls.editor_a,
  822. author=cls.author1,
  823. )
  824. cls.borrower1 = Borrower.objects.create(name="Jenny")
  825. cls.borrower2 = Borrower.objects.create(name="Kevin")
  826. # borrower 1 reserves, rents, and returns book1.
  827. Reservation.objects.create(
  828. borrower=cls.borrower1,
  829. book=cls.book1,
  830. state=Reservation.STOPPED,
  831. )
  832. RentalSession.objects.create(
  833. borrower=cls.borrower1,
  834. book=cls.book1,
  835. state=RentalSession.STOPPED,
  836. )
  837. # borrower2 reserves, rents, and returns book1.
  838. Reservation.objects.create(
  839. borrower=cls.borrower2,
  840. book=cls.book1,
  841. state=Reservation.STOPPED,
  842. )
  843. RentalSession.objects.create(
  844. borrower=cls.borrower2,
  845. book=cls.book1,
  846. state=RentalSession.STOPPED,
  847. )
  848. def test_aggregate(self):
  849. """
  850. filtered_relation() not only improves performance but also creates
  851. correct results when aggregating with multiple LEFT JOINs.
  852. Books can be reserved then rented by a borrower. Each reservation and
  853. rental session are recorded with Reservation and RentalSession models.
  854. Every time a reservation or a rental session is over, their state is
  855. changed to 'stopped'.
  856. Goal: Count number of books that are either currently reserved or
  857. rented by borrower1 or available.
  858. """
  859. qs = (
  860. Book.objects.annotate(
  861. is_reserved_or_rented_by=Case(
  862. When(
  863. reservation__state=Reservation.NEW,
  864. then=F("reservation__borrower__pk"),
  865. ),
  866. When(
  867. rental_session__state=RentalSession.NEW,
  868. then=F("rental_session__borrower__pk"),
  869. ),
  870. default=None,
  871. )
  872. )
  873. .filter(
  874. Q(is_reserved_or_rented_by=self.borrower1.pk) | Q(state=Book.AVAILABLE)
  875. )
  876. .distinct()
  877. )
  878. self.assertEqual(qs.count(), 1)
  879. # If count is equal to 1, the same aggregation should return in the
  880. # same result but it returns 4.
  881. self.assertSequenceEqual(
  882. qs.annotate(total=Count("pk")).values("total"), [{"total": 4}]
  883. )
  884. # With FilteredRelation, the result is as expected (1).
  885. qs = (
  886. Book.objects.annotate(
  887. active_reservations=FilteredRelation(
  888. "reservation",
  889. condition=Q(
  890. reservation__state=Reservation.NEW,
  891. reservation__borrower=self.borrower1,
  892. ),
  893. ),
  894. )
  895. .annotate(
  896. active_rental_sessions=FilteredRelation(
  897. "rental_session",
  898. condition=Q(
  899. rental_session__state=RentalSession.NEW,
  900. rental_session__borrower=self.borrower1,
  901. ),
  902. ),
  903. )
  904. .filter(
  905. (
  906. Q(active_reservations__isnull=False)
  907. | Q(active_rental_sessions__isnull=False)
  908. )
  909. | Q(state=Book.AVAILABLE)
  910. )
  911. .distinct()
  912. )
  913. self.assertEqual(qs.count(), 1)
  914. self.assertSequenceEqual(
  915. qs.annotate(total=Count("pk")).values("total"), [{"total": 1}]
  916. )
  917. def test_condition_spans_join(self):
  918. self.assertSequenceEqual(
  919. Book.objects.annotate(
  920. contains_editor_author=FilteredRelation(
  921. "author", condition=Q(author__name__icontains=F("editor__name"))
  922. )
  923. ).filter(
  924. contains_editor_author__isnull=False,
  925. ),
  926. [self.book1],
  927. )
  928. def test_condition_spans_join_chained(self):
  929. self.assertSequenceEqual(
  930. Book.objects.annotate(
  931. contains_editor_author=FilteredRelation(
  932. "author", condition=Q(author__name__icontains=F("editor__name"))
  933. ),
  934. contains_editor_author_ref=FilteredRelation(
  935. "author",
  936. condition=Q(author__name=F("contains_editor_author__name")),
  937. ),
  938. ).filter(
  939. contains_editor_author_ref__isnull=False,
  940. ),
  941. [self.book1],
  942. )
  943. def test_condition_self_ref(self):
  944. self.assertSequenceEqual(
  945. Book.objects.annotate(
  946. contains_author=FilteredRelation(
  947. "author",
  948. condition=Q(title__icontains=F("author__name")),
  949. )
  950. ).filter(
  951. contains_author__isnull=False,
  952. ),
  953. [self.book1],
  954. )
  955. class FilteredRelationAnalyticalAggregationTests(TestCase):
  956. @classmethod
  957. def setUpTestData(cls):
  958. author = Author.objects.create(name="Author")
  959. editor = Editor.objects.create(name="Editor")
  960. cls.book1 = Book.objects.create(
  961. title="Poem by Alice",
  962. editor=editor,
  963. author=author,
  964. )
  965. cls.book2 = Book.objects.create(
  966. title="The book by Jane A",
  967. editor=editor,
  968. author=author,
  969. )
  970. cls.book3 = Book.objects.create(
  971. title="The book by Jane B",
  972. editor=editor,
  973. author=author,
  974. )
  975. cls.seller1 = Seller.objects.create(name="Seller 1")
  976. cls.seller2 = Seller.objects.create(name="Seller 2")
  977. cls.usd = Currency.objects.create(currency="USD")
  978. cls.eur = Currency.objects.create(currency="EUR")
  979. cls.sales_date1 = date(2020, 7, 6)
  980. cls.sales_date2 = date(2020, 7, 7)
  981. ExchangeRate.objects.bulk_create(
  982. [
  983. ExchangeRate(
  984. rate_date=cls.sales_date1,
  985. from_currency=cls.usd,
  986. to_currency=cls.eur,
  987. rate=0.40,
  988. ),
  989. ExchangeRate(
  990. rate_date=cls.sales_date1,
  991. from_currency=cls.eur,
  992. to_currency=cls.usd,
  993. rate=1.60,
  994. ),
  995. ExchangeRate(
  996. rate_date=cls.sales_date2,
  997. from_currency=cls.usd,
  998. to_currency=cls.eur,
  999. rate=0.50,
  1000. ),
  1001. ExchangeRate(
  1002. rate_date=cls.sales_date2,
  1003. from_currency=cls.eur,
  1004. to_currency=cls.usd,
  1005. rate=1.50,
  1006. ),
  1007. ExchangeRate(
  1008. rate_date=cls.sales_date2,
  1009. from_currency=cls.usd,
  1010. to_currency=cls.usd,
  1011. rate=1.00,
  1012. ),
  1013. ]
  1014. )
  1015. BookDailySales.objects.bulk_create(
  1016. [
  1017. BookDailySales(
  1018. book=cls.book1,
  1019. sale_date=cls.sales_date1,
  1020. currency=cls.usd,
  1021. sales=100.00,
  1022. seller=cls.seller1,
  1023. ),
  1024. BookDailySales(
  1025. book=cls.book2,
  1026. sale_date=cls.sales_date1,
  1027. currency=cls.eur,
  1028. sales=200.00,
  1029. seller=cls.seller1,
  1030. ),
  1031. BookDailySales(
  1032. book=cls.book1,
  1033. sale_date=cls.sales_date2,
  1034. currency=cls.usd,
  1035. sales=50.00,
  1036. seller=cls.seller2,
  1037. ),
  1038. BookDailySales(
  1039. book=cls.book2,
  1040. sale_date=cls.sales_date2,
  1041. currency=cls.eur,
  1042. sales=100.00,
  1043. seller=cls.seller2,
  1044. ),
  1045. ]
  1046. )
  1047. def test_aggregate(self):
  1048. tests = [
  1049. Q(daily_sales__sale_date__gte=self.sales_date2),
  1050. ~Q(daily_sales__seller=self.seller1),
  1051. ]
  1052. for condition in tests:
  1053. with self.subTest(condition=condition):
  1054. qs = (
  1055. Book.objects.annotate(
  1056. recent_sales=FilteredRelation(
  1057. "daily_sales", condition=condition
  1058. ),
  1059. recent_sales_rates=FilteredRelation(
  1060. "recent_sales__currency__rates_from",
  1061. condition=Q(
  1062. recent_sales__currency__rates_from__rate_date=F(
  1063. "recent_sales__sale_date"
  1064. ),
  1065. recent_sales__currency__rates_from__to_currency=(
  1066. self.usd
  1067. ),
  1068. ),
  1069. ),
  1070. )
  1071. .annotate(
  1072. sales_sum=Sum(
  1073. F("recent_sales__sales") * F("recent_sales_rates__rate"),
  1074. output_field=DecimalField(),
  1075. ),
  1076. )
  1077. .values("title", "sales_sum")
  1078. .order_by(
  1079. F("sales_sum").desc(nulls_last=True),
  1080. )
  1081. )
  1082. self.assertSequenceEqual(
  1083. qs,
  1084. [
  1085. {"title": self.book2.title, "sales_sum": Decimal(150.00)},
  1086. {"title": self.book1.title, "sales_sum": Decimal(50.00)},
  1087. {"title": self.book3.title, "sales_sum": None},
  1088. ],
  1089. )