tests.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. from unittest import mock
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.core.exceptions import ObjectDoesNotExist
  4. from django.db import NotSupportedError, connection
  5. from django.db.models import Prefetch, QuerySet, prefetch_related_objects
  6. from django.db.models.query import get_prefetcher
  7. from django.db.models.sql import Query
  8. from django.test import (
  9. TestCase,
  10. override_settings,
  11. skipIfDBFeature,
  12. skipUnlessDBFeature,
  13. )
  14. from django.test.utils import CaptureQueriesContext
  15. from .models import (
  16. Article,
  17. Author,
  18. Author2,
  19. AuthorAddress,
  20. AuthorWithAge,
  21. Bio,
  22. Book,
  23. Bookmark,
  24. BookReview,
  25. BookWithYear,
  26. Comment,
  27. Department,
  28. Employee,
  29. FavoriteAuthors,
  30. House,
  31. LessonEntry,
  32. ModelIterableSubclass,
  33. Person,
  34. Qualification,
  35. Reader,
  36. Room,
  37. TaggedItem,
  38. Teacher,
  39. WordEntry,
  40. )
  41. class TestDataMixin:
  42. @classmethod
  43. def setUpTestData(cls):
  44. cls.book1 = Book.objects.create(title="Poems")
  45. cls.book2 = Book.objects.create(title="Jane Eyre")
  46. cls.book3 = Book.objects.create(title="Wuthering Heights")
  47. cls.book4 = Book.objects.create(title="Sense and Sensibility")
  48. cls.author1 = Author.objects.create(name="Charlotte", first_book=cls.book1)
  49. cls.author2 = Author.objects.create(name="Anne", first_book=cls.book1)
  50. cls.author3 = Author.objects.create(name="Emily", first_book=cls.book1)
  51. cls.author4 = Author.objects.create(name="Jane", first_book=cls.book4)
  52. cls.book1.authors.add(cls.author1, cls.author2, cls.author3)
  53. cls.book2.authors.add(cls.author1)
  54. cls.book3.authors.add(cls.author3)
  55. cls.book4.authors.add(cls.author4)
  56. cls.reader1 = Reader.objects.create(name="Amy")
  57. cls.reader2 = Reader.objects.create(name="Belinda")
  58. cls.reader1.books_read.add(cls.book1, cls.book4)
  59. cls.reader2.books_read.add(cls.book2, cls.book4)
  60. class PrefetchRelatedTests(TestDataMixin, TestCase):
  61. def assertWhereContains(self, sql, needle):
  62. where_idx = sql.index("WHERE")
  63. self.assertEqual(
  64. sql.count(str(needle), where_idx),
  65. 1,
  66. msg="WHERE clause doesn't contain %s, actual SQL: %s"
  67. % (needle, sql[where_idx:]),
  68. )
  69. def test_m2m_forward(self):
  70. with self.assertNumQueries(2):
  71. lists = [
  72. list(b.authors.all()) for b in Book.objects.prefetch_related("authors")
  73. ]
  74. normal_lists = [list(b.authors.all()) for b in Book.objects.all()]
  75. self.assertEqual(lists, normal_lists)
  76. def test_m2m_reverse(self):
  77. with self.assertNumQueries(2):
  78. lists = [
  79. list(a.books.all()) for a in Author.objects.prefetch_related("books")
  80. ]
  81. normal_lists = [list(a.books.all()) for a in Author.objects.all()]
  82. self.assertEqual(lists, normal_lists)
  83. def test_foreignkey_forward(self):
  84. with self.assertNumQueries(2):
  85. books = [
  86. a.first_book for a in Author.objects.prefetch_related("first_book")
  87. ]
  88. normal_books = [a.first_book for a in Author.objects.all()]
  89. self.assertEqual(books, normal_books)
  90. def test_foreignkey_reverse(self):
  91. with self.assertNumQueries(2):
  92. [
  93. list(b.first_time_authors.all())
  94. for b in Book.objects.prefetch_related("first_time_authors")
  95. ]
  96. self.assertSequenceEqual(self.book2.authors.all(), [self.author1])
  97. def test_onetoone_reverse_no_match(self):
  98. # Regression for #17439
  99. with self.assertNumQueries(2):
  100. book = Book.objects.prefetch_related("bookwithyear").all()[0]
  101. with self.assertNumQueries(0):
  102. with self.assertRaises(BookWithYear.DoesNotExist):
  103. book.bookwithyear
  104. def test_onetoone_reverse_with_to_field_pk(self):
  105. """
  106. A model (Bio) with a OneToOneField primary key (author) that references
  107. a non-pk field (name) on the related model (Author) is prefetchable.
  108. """
  109. Bio.objects.bulk_create(
  110. [
  111. Bio(author=self.author1),
  112. Bio(author=self.author2),
  113. Bio(author=self.author3),
  114. ]
  115. )
  116. authors = Author.objects.filter(
  117. name__in=[self.author1, self.author2, self.author3],
  118. ).prefetch_related("bio")
  119. with self.assertNumQueries(2):
  120. for author in authors:
  121. self.assertEqual(author.name, author.bio.author.name)
  122. def test_survives_clone(self):
  123. with self.assertNumQueries(2):
  124. [
  125. list(b.first_time_authors.all())
  126. for b in Book.objects.prefetch_related("first_time_authors").exclude(
  127. id=1000
  128. )
  129. ]
  130. def test_len(self):
  131. with self.assertNumQueries(2):
  132. qs = Book.objects.prefetch_related("first_time_authors")
  133. len(qs)
  134. [list(b.first_time_authors.all()) for b in qs]
  135. def test_bool(self):
  136. with self.assertNumQueries(2):
  137. qs = Book.objects.prefetch_related("first_time_authors")
  138. bool(qs)
  139. [list(b.first_time_authors.all()) for b in qs]
  140. def test_count(self):
  141. with self.assertNumQueries(2):
  142. qs = Book.objects.prefetch_related("first_time_authors")
  143. [b.first_time_authors.count() for b in qs]
  144. def test_exists(self):
  145. with self.assertNumQueries(2):
  146. qs = Book.objects.prefetch_related("first_time_authors")
  147. [b.first_time_authors.exists() for b in qs]
  148. def test_in_and_prefetch_related(self):
  149. """
  150. Regression test for #20242 - QuerySet "in" didn't work the first time
  151. when using prefetch_related. This was fixed by the removal of chunked
  152. reads from QuerySet iteration in
  153. 70679243d1786e03557c28929f9762a119e3ac14.
  154. """
  155. qs = Book.objects.prefetch_related("first_time_authors")
  156. self.assertIn(qs[0], qs)
  157. def test_clear(self):
  158. with self.assertNumQueries(5):
  159. with_prefetch = Author.objects.prefetch_related("books")
  160. without_prefetch = with_prefetch.prefetch_related(None)
  161. [list(a.books.all()) for a in without_prefetch]
  162. def test_m2m_then_m2m(self):
  163. """A m2m can be followed through another m2m."""
  164. with self.assertNumQueries(3):
  165. qs = Author.objects.prefetch_related("books__read_by")
  166. lists = [
  167. [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
  168. ]
  169. self.assertEqual(
  170. lists,
  171. [
  172. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  173. [["Amy"]], # Anne - Poems
  174. [["Amy"], []], # Emily - Poems, Wuthering Heights
  175. [["Amy", "Belinda"]], # Jane - Sense and Sense
  176. ],
  177. )
  178. def test_overriding_prefetch(self):
  179. with self.assertNumQueries(3):
  180. qs = Author.objects.prefetch_related("books", "books__read_by")
  181. lists = [
  182. [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
  183. ]
  184. self.assertEqual(
  185. lists,
  186. [
  187. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  188. [["Amy"]], # Anne - Poems
  189. [["Amy"], []], # Emily - Poems, Wuthering Heights
  190. [["Amy", "Belinda"]], # Jane - Sense and Sense
  191. ],
  192. )
  193. with self.assertNumQueries(3):
  194. qs = Author.objects.prefetch_related("books__read_by", "books")
  195. lists = [
  196. [[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
  197. ]
  198. self.assertEqual(
  199. lists,
  200. [
  201. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  202. [["Amy"]], # Anne - Poems
  203. [["Amy"], []], # Emily - Poems, Wuthering Heights
  204. [["Amy", "Belinda"]], # Jane - Sense and Sense
  205. ],
  206. )
  207. def test_get(self):
  208. """
  209. Objects retrieved with .get() get the prefetch behavior.
  210. """
  211. # Need a double
  212. with self.assertNumQueries(3):
  213. author = Author.objects.prefetch_related("books__read_by").get(
  214. name="Charlotte"
  215. )
  216. lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()]
  217. self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
  218. def test_foreign_key_then_m2m(self):
  219. """
  220. A m2m relation can be followed after a relation like ForeignKey that
  221. doesn't have many objects.
  222. """
  223. with self.assertNumQueries(2):
  224. qs = Author.objects.select_related("first_book").prefetch_related(
  225. "first_book__read_by"
  226. )
  227. lists = [[str(r) for r in a.first_book.read_by.all()] for a in qs]
  228. self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
  229. def test_reverse_one_to_one_then_m2m(self):
  230. """
  231. A m2m relation can be followed after going through the select_related
  232. reverse of an o2o.
  233. """
  234. qs = Author.objects.prefetch_related("bio__books").select_related("bio")
  235. with self.assertNumQueries(1):
  236. list(qs.all())
  237. Bio.objects.create(author=self.author1)
  238. with self.assertNumQueries(2):
  239. list(qs.all())
  240. def test_attribute_error(self):
  241. qs = Reader.objects.prefetch_related("books_read__xyz")
  242. msg = (
  243. "Cannot find 'xyz' on Book object, 'books_read__xyz' "
  244. "is an invalid parameter to prefetch_related()"
  245. )
  246. with self.assertRaisesMessage(AttributeError, msg) as cm:
  247. list(qs)
  248. self.assertIn("prefetch_related", str(cm.exception))
  249. def test_invalid_final_lookup(self):
  250. qs = Book.objects.prefetch_related("authors__name")
  251. msg = (
  252. "'authors__name' does not resolve to an item that supports "
  253. "prefetching - this is an invalid parameter to prefetch_related()."
  254. )
  255. with self.assertRaisesMessage(ValueError, msg) as cm:
  256. list(qs)
  257. self.assertIn("prefetch_related", str(cm.exception))
  258. self.assertIn("name", str(cm.exception))
  259. def test_prefetch_eq(self):
  260. prefetch_1 = Prefetch("authors", queryset=Author.objects.all())
  261. prefetch_2 = Prefetch("books", queryset=Book.objects.all())
  262. self.assertEqual(prefetch_1, prefetch_1)
  263. self.assertEqual(prefetch_1, mock.ANY)
  264. self.assertNotEqual(prefetch_1, prefetch_2)
  265. def test_forward_m2m_to_attr_conflict(self):
  266. msg = "to_attr=authors conflicts with a field on the Book model."
  267. authors = Author.objects.all()
  268. with self.assertRaisesMessage(ValueError, msg):
  269. list(
  270. Book.objects.prefetch_related(
  271. Prefetch("authors", queryset=authors, to_attr="authors"),
  272. )
  273. )
  274. # Without the ValueError, an author was deleted due to the implicit
  275. # save of the relation assignment.
  276. self.assertEqual(self.book1.authors.count(), 3)
  277. def test_reverse_m2m_to_attr_conflict(self):
  278. msg = "to_attr=books conflicts with a field on the Author model."
  279. poems = Book.objects.filter(title="Poems")
  280. with self.assertRaisesMessage(ValueError, msg):
  281. list(
  282. Author.objects.prefetch_related(
  283. Prefetch("books", queryset=poems, to_attr="books"),
  284. )
  285. )
  286. # Without the ValueError, a book was deleted due to the implicit
  287. # save of reverse relation assignment.
  288. self.assertEqual(self.author1.books.count(), 2)
  289. def test_m2m_then_reverse_fk_object_ids(self):
  290. with CaptureQueriesContext(connection) as queries:
  291. list(Book.objects.prefetch_related("authors__addresses"))
  292. sql = queries[-1]["sql"]
  293. self.assertWhereContains(sql, self.author1.name)
  294. def test_m2m_then_m2m_object_ids(self):
  295. with CaptureQueriesContext(connection) as queries:
  296. list(Book.objects.prefetch_related("authors__favorite_authors"))
  297. sql = queries[-1]["sql"]
  298. self.assertWhereContains(sql, self.author1.name)
  299. def test_m2m_then_reverse_one_to_one_object_ids(self):
  300. with CaptureQueriesContext(connection) as queries:
  301. list(Book.objects.prefetch_related("authors__authorwithage"))
  302. sql = queries[-1]["sql"]
  303. self.assertWhereContains(sql, self.author1.id)
  304. def test_filter_deferred(self):
  305. """
  306. Related filtering of prefetched querysets is deferred on m2m and
  307. reverse m2o relations until necessary.
  308. """
  309. add_q = Query.add_q
  310. for relation in ["authors", "first_time_authors"]:
  311. with self.subTest(relation=relation):
  312. with mock.patch.object(
  313. Query,
  314. "add_q",
  315. autospec=True,
  316. side_effect=lambda self, q: add_q(self, q),
  317. ) as add_q_mock:
  318. list(Book.objects.prefetch_related(relation))
  319. self.assertEqual(add_q_mock.call_count, 1)
  320. def test_named_values_list(self):
  321. qs = Author.objects.prefetch_related("books")
  322. self.assertCountEqual(
  323. [value.name for value in qs.values_list("name", named=True)],
  324. ["Anne", "Charlotte", "Emily", "Jane"],
  325. )
  326. def test_m2m_prefetching_iterator_with_chunks(self):
  327. with self.assertNumQueries(3):
  328. authors = [
  329. b.authors.first()
  330. for b in Book.objects.prefetch_related("authors").iterator(chunk_size=2)
  331. ]
  332. self.assertEqual(
  333. authors,
  334. [self.author1, self.author1, self.author3, self.author4],
  335. )
  336. def test_m2m_prefetching_iterator_without_chunks_error(self):
  337. msg = (
  338. "chunk_size must be provided when using QuerySet.iterator() after "
  339. "prefetch_related()."
  340. )
  341. with self.assertRaisesMessage(ValueError, msg):
  342. Book.objects.prefetch_related("authors").iterator()
  343. class RawQuerySetTests(TestDataMixin, TestCase):
  344. def test_basic(self):
  345. with self.assertNumQueries(2):
  346. books = Book.objects.raw(
  347. "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,)
  348. ).prefetch_related("authors")
  349. book1 = list(books)[0]
  350. with self.assertNumQueries(0):
  351. self.assertCountEqual(
  352. book1.authors.all(), [self.author1, self.author2, self.author3]
  353. )
  354. def test_prefetch_before_raw(self):
  355. with self.assertNumQueries(2):
  356. books = Book.objects.prefetch_related("authors").raw(
  357. "SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,)
  358. )
  359. book1 = list(books)[0]
  360. with self.assertNumQueries(0):
  361. self.assertCountEqual(
  362. book1.authors.all(), [self.author1, self.author2, self.author3]
  363. )
  364. def test_clear(self):
  365. with self.assertNumQueries(5):
  366. with_prefetch = Author.objects.raw(
  367. "SELECT * FROM prefetch_related_author"
  368. ).prefetch_related("books")
  369. without_prefetch = with_prefetch.prefetch_related(None)
  370. [list(a.books.all()) for a in without_prefetch]
  371. class CustomPrefetchTests(TestCase):
  372. @classmethod
  373. def traverse_qs(cls, obj_iter, path):
  374. """
  375. Helper method that returns a list containing a list of the objects in the
  376. obj_iter. Then for each object in the obj_iter, the path will be
  377. recursively travelled and the found objects are added to the return value.
  378. """
  379. ret_val = []
  380. if hasattr(obj_iter, "all"):
  381. obj_iter = obj_iter.all()
  382. try:
  383. iter(obj_iter)
  384. except TypeError:
  385. obj_iter = [obj_iter]
  386. for obj in obj_iter:
  387. rel_objs = []
  388. for part in path:
  389. if not part:
  390. continue
  391. try:
  392. related = getattr(obj, part[0])
  393. except ObjectDoesNotExist:
  394. continue
  395. if related is not None:
  396. rel_objs.extend(cls.traverse_qs(related, [part[1:]]))
  397. ret_val.append((obj, rel_objs))
  398. return ret_val
  399. @classmethod
  400. def setUpTestData(cls):
  401. cls.person1 = Person.objects.create(name="Joe")
  402. cls.person2 = Person.objects.create(name="Mary")
  403. # Set main_room for each house before creating the next one for
  404. # databases where supports_nullable_unique_constraints is False.
  405. cls.house1 = House.objects.create(
  406. name="House 1", address="123 Main St", owner=cls.person1
  407. )
  408. cls.room1_1 = Room.objects.create(name="Dining room", house=cls.house1)
  409. cls.room1_2 = Room.objects.create(name="Lounge", house=cls.house1)
  410. cls.room1_3 = Room.objects.create(name="Kitchen", house=cls.house1)
  411. cls.house1.main_room = cls.room1_1
  412. cls.house1.save()
  413. cls.person1.houses.add(cls.house1)
  414. cls.house2 = House.objects.create(
  415. name="House 2", address="45 Side St", owner=cls.person1
  416. )
  417. cls.room2_1 = Room.objects.create(name="Dining room", house=cls.house2)
  418. cls.room2_2 = Room.objects.create(name="Lounge", house=cls.house2)
  419. cls.room2_3 = Room.objects.create(name="Kitchen", house=cls.house2)
  420. cls.house2.main_room = cls.room2_1
  421. cls.house2.save()
  422. cls.person1.houses.add(cls.house2)
  423. cls.house3 = House.objects.create(
  424. name="House 3", address="6 Downing St", owner=cls.person2
  425. )
  426. cls.room3_1 = Room.objects.create(name="Dining room", house=cls.house3)
  427. cls.room3_2 = Room.objects.create(name="Lounge", house=cls.house3)
  428. cls.room3_3 = Room.objects.create(name="Kitchen", house=cls.house3)
  429. cls.house3.main_room = cls.room3_1
  430. cls.house3.save()
  431. cls.person2.houses.add(cls.house3)
  432. cls.house4 = House.objects.create(
  433. name="house 4", address="7 Regents St", owner=cls.person2
  434. )
  435. cls.room4_1 = Room.objects.create(name="Dining room", house=cls.house4)
  436. cls.room4_2 = Room.objects.create(name="Lounge", house=cls.house4)
  437. cls.room4_3 = Room.objects.create(name="Kitchen", house=cls.house4)
  438. cls.house4.main_room = cls.room4_1
  439. cls.house4.save()
  440. cls.person2.houses.add(cls.house4)
  441. def test_traverse_qs(self):
  442. qs = Person.objects.prefetch_related("houses")
  443. related_objs_normal = ([list(p.houses.all()) for p in qs],)
  444. related_objs_from_traverse = [
  445. [inner[0] for inner in o[1]] for o in self.traverse_qs(qs, [["houses"]])
  446. ]
  447. self.assertEqual(related_objs_normal, (related_objs_from_traverse,))
  448. def test_ambiguous(self):
  449. # Ambiguous: Lookup was already seen with a different queryset.
  450. msg = (
  451. "'houses' lookup was already seen with a different queryset. You "
  452. "may need to adjust the ordering of your lookups."
  453. )
  454. # lookup.queryset shouldn't be evaluated.
  455. with self.assertNumQueries(3):
  456. with self.assertRaisesMessage(ValueError, msg):
  457. self.traverse_qs(
  458. Person.objects.prefetch_related(
  459. "houses__rooms",
  460. Prefetch("houses", queryset=House.objects.all()),
  461. ),
  462. [["houses", "rooms"]],
  463. )
  464. # Ambiguous: Lookup houses_lst doesn't yet exist when performing
  465. # houses_lst__rooms.
  466. msg = (
  467. "Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is "
  468. "an invalid parameter to prefetch_related()"
  469. )
  470. with self.assertRaisesMessage(AttributeError, msg):
  471. self.traverse_qs(
  472. Person.objects.prefetch_related(
  473. "houses_lst__rooms",
  474. Prefetch(
  475. "houses", queryset=House.objects.all(), to_attr="houses_lst"
  476. ),
  477. ),
  478. [["houses", "rooms"]],
  479. )
  480. # Not ambiguous.
  481. self.traverse_qs(
  482. Person.objects.prefetch_related("houses__rooms", "houses"),
  483. [["houses", "rooms"]],
  484. )
  485. self.traverse_qs(
  486. Person.objects.prefetch_related(
  487. "houses__rooms",
  488. Prefetch("houses", queryset=House.objects.all(), to_attr="houses_lst"),
  489. ),
  490. [["houses", "rooms"]],
  491. )
  492. def test_m2m(self):
  493. # Control lookups.
  494. with self.assertNumQueries(2):
  495. lst1 = self.traverse_qs(
  496. Person.objects.prefetch_related("houses"), [["houses"]]
  497. )
  498. # Test lookups.
  499. with self.assertNumQueries(2):
  500. lst2 = self.traverse_qs(
  501. Person.objects.prefetch_related(Prefetch("houses")), [["houses"]]
  502. )
  503. self.assertEqual(lst1, lst2)
  504. with self.assertNumQueries(2):
  505. lst2 = self.traverse_qs(
  506. Person.objects.prefetch_related(
  507. Prefetch("houses", to_attr="houses_lst")
  508. ),
  509. [["houses_lst"]],
  510. )
  511. self.assertEqual(lst1, lst2)
  512. def test_reverse_m2m(self):
  513. # Control lookups.
  514. with self.assertNumQueries(2):
  515. lst1 = self.traverse_qs(
  516. House.objects.prefetch_related("occupants"), [["occupants"]]
  517. )
  518. # Test lookups.
  519. with self.assertNumQueries(2):
  520. lst2 = self.traverse_qs(
  521. House.objects.prefetch_related(Prefetch("occupants")), [["occupants"]]
  522. )
  523. self.assertEqual(lst1, lst2)
  524. with self.assertNumQueries(2):
  525. lst2 = self.traverse_qs(
  526. House.objects.prefetch_related(
  527. Prefetch("occupants", to_attr="occupants_lst")
  528. ),
  529. [["occupants_lst"]],
  530. )
  531. self.assertEqual(lst1, lst2)
  532. def test_m2m_through_fk(self):
  533. # Control lookups.
  534. with self.assertNumQueries(3):
  535. lst1 = self.traverse_qs(
  536. Room.objects.prefetch_related("house__occupants"),
  537. [["house", "occupants"]],
  538. )
  539. # Test lookups.
  540. with self.assertNumQueries(3):
  541. lst2 = self.traverse_qs(
  542. Room.objects.prefetch_related(Prefetch("house__occupants")),
  543. [["house", "occupants"]],
  544. )
  545. self.assertEqual(lst1, lst2)
  546. with self.assertNumQueries(3):
  547. lst2 = self.traverse_qs(
  548. Room.objects.prefetch_related(
  549. Prefetch("house__occupants", to_attr="occupants_lst")
  550. ),
  551. [["house", "occupants_lst"]],
  552. )
  553. self.assertEqual(lst1, lst2)
  554. def test_m2m_through_gfk(self):
  555. TaggedItem.objects.create(tag="houses", content_object=self.house1)
  556. TaggedItem.objects.create(tag="houses", content_object=self.house2)
  557. # Control lookups.
  558. with self.assertNumQueries(3):
  559. lst1 = self.traverse_qs(
  560. TaggedItem.objects.filter(tag="houses").prefetch_related(
  561. "content_object__rooms"
  562. ),
  563. [["content_object", "rooms"]],
  564. )
  565. # Test lookups.
  566. with self.assertNumQueries(3):
  567. lst2 = self.traverse_qs(
  568. TaggedItem.objects.prefetch_related(
  569. Prefetch("content_object"),
  570. Prefetch("content_object__rooms", to_attr="rooms_lst"),
  571. ),
  572. [["content_object", "rooms_lst"]],
  573. )
  574. self.assertEqual(lst1, lst2)
  575. def test_o2m_through_m2m(self):
  576. # Control lookups.
  577. with self.assertNumQueries(3):
  578. lst1 = self.traverse_qs(
  579. Person.objects.prefetch_related("houses", "houses__rooms"),
  580. [["houses", "rooms"]],
  581. )
  582. # Test lookups.
  583. with self.assertNumQueries(3):
  584. lst2 = self.traverse_qs(
  585. Person.objects.prefetch_related(Prefetch("houses"), "houses__rooms"),
  586. [["houses", "rooms"]],
  587. )
  588. self.assertEqual(lst1, lst2)
  589. with self.assertNumQueries(3):
  590. lst2 = self.traverse_qs(
  591. Person.objects.prefetch_related(
  592. Prefetch("houses"), Prefetch("houses__rooms")
  593. ),
  594. [["houses", "rooms"]],
  595. )
  596. self.assertEqual(lst1, lst2)
  597. with self.assertNumQueries(3):
  598. lst2 = self.traverse_qs(
  599. Person.objects.prefetch_related(
  600. Prefetch("houses", to_attr="houses_lst"), "houses_lst__rooms"
  601. ),
  602. [["houses_lst", "rooms"]],
  603. )
  604. self.assertEqual(lst1, lst2)
  605. with self.assertNumQueries(3):
  606. lst2 = self.traverse_qs(
  607. Person.objects.prefetch_related(
  608. Prefetch("houses", to_attr="houses_lst"),
  609. Prefetch("houses_lst__rooms", to_attr="rooms_lst"),
  610. ),
  611. [["houses_lst", "rooms_lst"]],
  612. )
  613. self.assertEqual(lst1, lst2)
  614. def test_generic_rel(self):
  615. bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
  616. TaggedItem.objects.create(content_object=bookmark, tag="django")
  617. TaggedItem.objects.create(
  618. content_object=bookmark, favorite=bookmark, tag="python"
  619. )
  620. # Control lookups.
  621. with self.assertNumQueries(4):
  622. lst1 = self.traverse_qs(
  623. Bookmark.objects.prefetch_related(
  624. "tags", "tags__content_object", "favorite_tags"
  625. ),
  626. [["tags", "content_object"], ["favorite_tags"]],
  627. )
  628. # Test lookups.
  629. with self.assertNumQueries(4):
  630. lst2 = self.traverse_qs(
  631. Bookmark.objects.prefetch_related(
  632. Prefetch("tags", to_attr="tags_lst"),
  633. Prefetch("tags_lst__content_object"),
  634. Prefetch("favorite_tags"),
  635. ),
  636. [["tags_lst", "content_object"], ["favorite_tags"]],
  637. )
  638. self.assertEqual(lst1, lst2)
  639. def test_traverse_single_item_property(self):
  640. # Control lookups.
  641. with self.assertNumQueries(5):
  642. lst1 = self.traverse_qs(
  643. Person.objects.prefetch_related(
  644. "houses__rooms",
  645. "primary_house__occupants__houses",
  646. ),
  647. [["primary_house", "occupants", "houses"]],
  648. )
  649. # Test lookups.
  650. with self.assertNumQueries(5):
  651. lst2 = self.traverse_qs(
  652. Person.objects.prefetch_related(
  653. "houses__rooms",
  654. Prefetch("primary_house__occupants", to_attr="occupants_lst"),
  655. "primary_house__occupants_lst__houses",
  656. ),
  657. [["primary_house", "occupants_lst", "houses"]],
  658. )
  659. self.assertEqual(lst1, lst2)
  660. def test_traverse_multiple_items_property(self):
  661. # Control lookups.
  662. with self.assertNumQueries(4):
  663. lst1 = self.traverse_qs(
  664. Person.objects.prefetch_related(
  665. "houses",
  666. "all_houses__occupants__houses",
  667. ),
  668. [["all_houses", "occupants", "houses"]],
  669. )
  670. # Test lookups.
  671. with self.assertNumQueries(4):
  672. lst2 = self.traverse_qs(
  673. Person.objects.prefetch_related(
  674. "houses",
  675. Prefetch("all_houses__occupants", to_attr="occupants_lst"),
  676. "all_houses__occupants_lst__houses",
  677. ),
  678. [["all_houses", "occupants_lst", "houses"]],
  679. )
  680. self.assertEqual(lst1, lst2)
  681. def test_custom_qs(self):
  682. # Test basic.
  683. with self.assertNumQueries(2):
  684. lst1 = list(Person.objects.prefetch_related("houses"))
  685. with self.assertNumQueries(2):
  686. lst2 = list(
  687. Person.objects.prefetch_related(
  688. Prefetch(
  689. "houses", queryset=House.objects.all(), to_attr="houses_lst"
  690. )
  691. )
  692. )
  693. self.assertEqual(
  694. self.traverse_qs(lst1, [["houses"]]),
  695. self.traverse_qs(lst2, [["houses_lst"]]),
  696. )
  697. # Test queryset filtering.
  698. with self.assertNumQueries(2):
  699. lst2 = list(
  700. Person.objects.prefetch_related(
  701. Prefetch(
  702. "houses",
  703. queryset=House.objects.filter(
  704. pk__in=[self.house1.pk, self.house3.pk]
  705. ),
  706. to_attr="houses_lst",
  707. )
  708. )
  709. )
  710. self.assertEqual(len(lst2[0].houses_lst), 1)
  711. self.assertEqual(lst2[0].houses_lst[0], self.house1)
  712. self.assertEqual(len(lst2[1].houses_lst), 1)
  713. self.assertEqual(lst2[1].houses_lst[0], self.house3)
  714. # Test flattened.
  715. with self.assertNumQueries(3):
  716. lst1 = list(Person.objects.prefetch_related("houses__rooms"))
  717. with self.assertNumQueries(3):
  718. lst2 = list(
  719. Person.objects.prefetch_related(
  720. Prefetch(
  721. "houses__rooms",
  722. queryset=Room.objects.all(),
  723. to_attr="rooms_lst",
  724. )
  725. )
  726. )
  727. self.assertEqual(
  728. self.traverse_qs(lst1, [["houses", "rooms"]]),
  729. self.traverse_qs(lst2, [["houses", "rooms_lst"]]),
  730. )
  731. # Test inner select_related.
  732. with self.assertNumQueries(3):
  733. lst1 = list(Person.objects.prefetch_related("houses__owner"))
  734. with self.assertNumQueries(2):
  735. lst2 = list(
  736. Person.objects.prefetch_related(
  737. Prefetch("houses", queryset=House.objects.select_related("owner"))
  738. )
  739. )
  740. self.assertEqual(
  741. self.traverse_qs(lst1, [["houses", "owner"]]),
  742. self.traverse_qs(lst2, [["houses", "owner"]]),
  743. )
  744. # Test inner prefetch.
  745. inner_rooms_qs = Room.objects.filter(pk__in=[self.room1_1.pk, self.room1_2.pk])
  746. houses_qs_prf = House.objects.prefetch_related(
  747. Prefetch("rooms", queryset=inner_rooms_qs, to_attr="rooms_lst")
  748. )
  749. with self.assertNumQueries(4):
  750. lst2 = list(
  751. Person.objects.prefetch_related(
  752. Prefetch(
  753. "houses",
  754. queryset=houses_qs_prf.filter(pk=self.house1.pk),
  755. to_attr="houses_lst",
  756. ),
  757. Prefetch("houses_lst__rooms_lst__main_room_of"),
  758. )
  759. )
  760. self.assertEqual(len(lst2[0].houses_lst[0].rooms_lst), 2)
  761. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0], self.room1_1)
  762. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[1], self.room1_2)
  763. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0].main_room_of, self.house1)
  764. self.assertEqual(len(lst2[1].houses_lst), 0)
  765. # Test ForwardManyToOneDescriptor.
  766. houses = House.objects.select_related("owner")
  767. with self.assertNumQueries(6):
  768. rooms = Room.objects.prefetch_related("house")
  769. lst1 = self.traverse_qs(rooms, [["house", "owner"]])
  770. with self.assertNumQueries(2):
  771. rooms = Room.objects.prefetch_related(Prefetch("house", queryset=houses))
  772. lst2 = self.traverse_qs(rooms, [["house", "owner"]])
  773. self.assertEqual(lst1, lst2)
  774. with self.assertNumQueries(2):
  775. houses = House.objects.select_related("owner")
  776. rooms = Room.objects.prefetch_related(
  777. Prefetch("house", queryset=houses, to_attr="house_attr")
  778. )
  779. lst2 = self.traverse_qs(rooms, [["house_attr", "owner"]])
  780. self.assertEqual(lst1, lst2)
  781. room = Room.objects.prefetch_related(
  782. Prefetch("house", queryset=houses.filter(address="DoesNotExist"))
  783. ).first()
  784. with self.assertRaises(ObjectDoesNotExist):
  785. getattr(room, "house")
  786. room = Room.objects.prefetch_related(
  787. Prefetch(
  788. "house",
  789. queryset=houses.filter(address="DoesNotExist"),
  790. to_attr="house_attr",
  791. )
  792. ).first()
  793. self.assertIsNone(room.house_attr)
  794. rooms = Room.objects.prefetch_related(
  795. Prefetch("house", queryset=House.objects.only("name"))
  796. )
  797. with self.assertNumQueries(2):
  798. getattr(rooms.first().house, "name")
  799. with self.assertNumQueries(3):
  800. getattr(rooms.first().house, "address")
  801. # Test ReverseOneToOneDescriptor.
  802. houses = House.objects.select_related("owner")
  803. with self.assertNumQueries(6):
  804. rooms = Room.objects.prefetch_related("main_room_of")
  805. lst1 = self.traverse_qs(rooms, [["main_room_of", "owner"]])
  806. with self.assertNumQueries(2):
  807. rooms = Room.objects.prefetch_related(
  808. Prefetch("main_room_of", queryset=houses)
  809. )
  810. lst2 = self.traverse_qs(rooms, [["main_room_of", "owner"]])
  811. self.assertEqual(lst1, lst2)
  812. with self.assertNumQueries(2):
  813. rooms = list(
  814. Room.objects.prefetch_related(
  815. Prefetch(
  816. "main_room_of",
  817. queryset=houses,
  818. to_attr="main_room_of_attr",
  819. )
  820. )
  821. )
  822. lst2 = self.traverse_qs(rooms, [["main_room_of_attr", "owner"]])
  823. self.assertEqual(lst1, lst2)
  824. room = (
  825. Room.objects.filter(main_room_of__isnull=False)
  826. .prefetch_related(
  827. Prefetch("main_room_of", queryset=houses.filter(address="DoesNotExist"))
  828. )
  829. .first()
  830. )
  831. with self.assertRaises(ObjectDoesNotExist):
  832. getattr(room, "main_room_of")
  833. room = (
  834. Room.objects.filter(main_room_of__isnull=False)
  835. .prefetch_related(
  836. Prefetch(
  837. "main_room_of",
  838. queryset=houses.filter(address="DoesNotExist"),
  839. to_attr="main_room_of_attr",
  840. )
  841. )
  842. .first()
  843. )
  844. self.assertIsNone(room.main_room_of_attr)
  845. # The custom queryset filters should be applied to the queryset
  846. # instance returned by the manager.
  847. person = Person.objects.prefetch_related(
  848. Prefetch("houses", queryset=House.objects.filter(name="House 1")),
  849. ).get(pk=self.person1.pk)
  850. self.assertEqual(
  851. list(person.houses.all()),
  852. list(person.houses.all().all()),
  853. )
  854. def test_nested_prefetch_related_are_not_overwritten(self):
  855. # Regression test for #24873
  856. houses_2 = House.objects.prefetch_related(Prefetch("rooms"))
  857. persons = Person.objects.prefetch_related(Prefetch("houses", queryset=houses_2))
  858. houses = House.objects.prefetch_related(Prefetch("occupants", queryset=persons))
  859. list(houses) # queryset must be evaluated once to reproduce the bug.
  860. self.assertEqual(
  861. houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0],
  862. self.room2_1,
  863. )
  864. def test_nested_prefetch_related_with_duplicate_prefetcher(self):
  865. """
  866. Nested prefetches whose name clashes with descriptor names
  867. (Person.houses here) are allowed.
  868. """
  869. occupants = Person.objects.prefetch_related(
  870. Prefetch("houses", to_attr="some_attr_name"),
  871. Prefetch("houses", queryset=House.objects.prefetch_related("main_room")),
  872. )
  873. houses = House.objects.prefetch_related(
  874. Prefetch("occupants", queryset=occupants)
  875. )
  876. with self.assertNumQueries(5):
  877. self.traverse_qs(list(houses), [["occupants", "houses", "main_room"]])
  878. def test_values_queryset(self):
  879. msg = "Prefetch querysets cannot use raw(), values(), and values_list()."
  880. with self.assertRaisesMessage(ValueError, msg):
  881. Prefetch("houses", House.objects.values("pk"))
  882. with self.assertRaisesMessage(ValueError, msg):
  883. Prefetch("houses", House.objects.values_list("pk"))
  884. # That error doesn't affect managers with custom ModelIterable subclasses
  885. self.assertIs(
  886. Teacher.objects_custom.all()._iterable_class, ModelIterableSubclass
  887. )
  888. Prefetch("teachers", Teacher.objects_custom.all())
  889. def test_raw_queryset(self):
  890. msg = "Prefetch querysets cannot use raw(), values(), and values_list()."
  891. with self.assertRaisesMessage(ValueError, msg):
  892. Prefetch("houses", House.objects.raw("select pk from house"))
  893. def test_to_attr_doesnt_cache_through_attr_as_list(self):
  894. house = House.objects.prefetch_related(
  895. Prefetch("rooms", queryset=Room.objects.all(), to_attr="to_rooms"),
  896. ).get(pk=self.house3.pk)
  897. self.assertIsInstance(house.rooms.all(), QuerySet)
  898. def test_to_attr_cached_property(self):
  899. persons = Person.objects.prefetch_related(
  900. Prefetch("houses", House.objects.all(), to_attr="cached_all_houses"),
  901. )
  902. for person in persons:
  903. # To bypass caching at the related descriptor level, don't use
  904. # person.houses.all() here.
  905. all_houses = list(House.objects.filter(occupants=person))
  906. with self.assertNumQueries(0):
  907. self.assertEqual(person.cached_all_houses, all_houses)
  908. def test_filter_deferred(self):
  909. """
  910. Related filtering of prefetched querysets is deferred until necessary.
  911. """
  912. add_q = Query.add_q
  913. with mock.patch.object(
  914. Query,
  915. "add_q",
  916. autospec=True,
  917. side_effect=lambda self, q: add_q(self, q),
  918. ) as add_q_mock:
  919. list(
  920. House.objects.prefetch_related(
  921. Prefetch("occupants", queryset=Person.objects.all())
  922. )
  923. )
  924. self.assertEqual(add_q_mock.call_count, 1)
  925. class DefaultManagerTests(TestCase):
  926. @classmethod
  927. def setUpTestData(cls):
  928. cls.qual1 = Qualification.objects.create(name="BA")
  929. cls.qual2 = Qualification.objects.create(name="BSci")
  930. cls.qual3 = Qualification.objects.create(name="MA")
  931. cls.qual4 = Qualification.objects.create(name="PhD")
  932. cls.teacher1 = Teacher.objects.create(name="Mr Cleese")
  933. cls.teacher2 = Teacher.objects.create(name="Mr Idle")
  934. cls.teacher3 = Teacher.objects.create(name="Mr Chapman")
  935. cls.teacher1.qualifications.add(cls.qual1, cls.qual2, cls.qual3, cls.qual4)
  936. cls.teacher2.qualifications.add(cls.qual1)
  937. cls.teacher3.qualifications.add(cls.qual2)
  938. cls.dept1 = Department.objects.create(name="English")
  939. cls.dept2 = Department.objects.create(name="Physics")
  940. cls.dept1.teachers.add(cls.teacher1, cls.teacher2)
  941. cls.dept2.teachers.add(cls.teacher1, cls.teacher3)
  942. def test_m2m_then_m2m(self):
  943. with self.assertNumQueries(3):
  944. # When we prefetch the teachers, and force the query, we don't want
  945. # the default manager on teachers to immediately get all the related
  946. # qualifications, since this will do one query per teacher.
  947. qs = Department.objects.prefetch_related("teachers")
  948. depts = "".join(
  949. "%s department: %s\n"
  950. % (dept.name, ", ".join(str(t) for t in dept.teachers.all()))
  951. for dept in qs
  952. )
  953. self.assertEqual(
  954. depts,
  955. "English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
  956. "Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman "
  957. "(BSci)\n",
  958. )
  959. class GenericRelationTests(TestCase):
  960. @classmethod
  961. def setUpTestData(cls):
  962. book1 = Book.objects.create(title="Winnie the Pooh")
  963. book2 = Book.objects.create(title="Do you like green eggs and spam?")
  964. book3 = Book.objects.create(title="Three Men In A Boat")
  965. reader1 = Reader.objects.create(name="me")
  966. reader2 = Reader.objects.create(name="you")
  967. reader3 = Reader.objects.create(name="someone")
  968. book1.read_by.add(reader1, reader2)
  969. book2.read_by.add(reader2)
  970. book3.read_by.add(reader3)
  971. cls.book1, cls.book2, cls.book3 = book1, book2, book3
  972. cls.reader1, cls.reader2, cls.reader3 = reader1, reader2, reader3
  973. def test_prefetch_GFK(self):
  974. TaggedItem.objects.create(tag="awesome", content_object=self.book1)
  975. TaggedItem.objects.create(tag="great", content_object=self.reader1)
  976. TaggedItem.objects.create(tag="outstanding", content_object=self.book2)
  977. TaggedItem.objects.create(tag="amazing", content_object=self.reader3)
  978. # 1 for TaggedItem table, 1 for Book table, 1 for Reader table
  979. with self.assertNumQueries(3):
  980. qs = TaggedItem.objects.prefetch_related("content_object")
  981. list(qs)
  982. def test_prefetch_GFK_nonint_pk(self):
  983. Comment.objects.create(comment="awesome", content_object=self.book1)
  984. # 1 for Comment table, 1 for Book table
  985. with self.assertNumQueries(2):
  986. qs = Comment.objects.prefetch_related("content_object")
  987. [c.content_object for c in qs]
  988. def test_prefetch_GFK_uuid_pk(self):
  989. article = Article.objects.create(name="Django")
  990. Comment.objects.create(comment="awesome", content_object_uuid=article)
  991. qs = Comment.objects.prefetch_related("content_object_uuid")
  992. self.assertEqual([c.content_object_uuid for c in qs], [article])
  993. def test_prefetch_GFK_fk_pk(self):
  994. book = Book.objects.create(title="Poems")
  995. book_with_year = BookWithYear.objects.create(book=book, published_year=2019)
  996. Comment.objects.create(comment="awesome", content_object=book_with_year)
  997. qs = Comment.objects.prefetch_related("content_object")
  998. self.assertEqual([c.content_object for c in qs], [book_with_year])
  999. def test_traverse_GFK(self):
  1000. """
  1001. A 'content_object' can be traversed with prefetch_related() and
  1002. get to related objects on the other side (assuming it is suitably
  1003. filtered)
  1004. """
  1005. TaggedItem.objects.create(tag="awesome", content_object=self.book1)
  1006. TaggedItem.objects.create(tag="awesome", content_object=self.book2)
  1007. TaggedItem.objects.create(tag="awesome", content_object=self.book3)
  1008. TaggedItem.objects.create(tag="awesome", content_object=self.reader1)
  1009. TaggedItem.objects.create(tag="awesome", content_object=self.reader2)
  1010. ct = ContentType.objects.get_for_model(Book)
  1011. # We get 3 queries - 1 for main query, 1 for content_objects since they
  1012. # all use the same table, and 1 for the 'read_by' relation.
  1013. with self.assertNumQueries(3):
  1014. # If we limit to books, we know that they will have 'read_by'
  1015. # attributes, so the following makes sense:
  1016. qs = TaggedItem.objects.filter(
  1017. content_type=ct, tag="awesome"
  1018. ).prefetch_related("content_object__read_by")
  1019. readers_of_awesome_books = {
  1020. r.name for tag in qs for r in tag.content_object.read_by.all()
  1021. }
  1022. self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"})
  1023. def test_nullable_GFK(self):
  1024. TaggedItem.objects.create(
  1025. tag="awesome", content_object=self.book1, created_by=self.reader1
  1026. )
  1027. TaggedItem.objects.create(tag="great", content_object=self.book2)
  1028. TaggedItem.objects.create(tag="rubbish", content_object=self.book3)
  1029. with self.assertNumQueries(2):
  1030. result = [
  1031. t.created_by for t in TaggedItem.objects.prefetch_related("created_by")
  1032. ]
  1033. self.assertEqual(result, [t.created_by for t in TaggedItem.objects.all()])
  1034. def test_generic_relation(self):
  1035. bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
  1036. TaggedItem.objects.create(content_object=bookmark, tag="django")
  1037. TaggedItem.objects.create(content_object=bookmark, tag="python")
  1038. with self.assertNumQueries(2):
  1039. tags = [
  1040. t.tag
  1041. for b in Bookmark.objects.prefetch_related("tags")
  1042. for t in b.tags.all()
  1043. ]
  1044. self.assertEqual(sorted(tags), ["django", "python"])
  1045. def test_charfield_GFK(self):
  1046. b = Bookmark.objects.create(url="http://www.djangoproject.com/")
  1047. TaggedItem.objects.create(content_object=b, tag="django")
  1048. TaggedItem.objects.create(content_object=b, favorite=b, tag="python")
  1049. with self.assertNumQueries(3):
  1050. bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related(
  1051. "tags", "favorite_tags"
  1052. )[0]
  1053. self.assertEqual(
  1054. sorted(i.tag for i in bookmark.tags.all()), ["django", "python"]
  1055. )
  1056. self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
  1057. def test_custom_queryset(self):
  1058. bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
  1059. django_tag = TaggedItem.objects.create(content_object=bookmark, tag="django")
  1060. TaggedItem.objects.create(content_object=bookmark, tag="python")
  1061. with self.assertNumQueries(2):
  1062. bookmark = Bookmark.objects.prefetch_related(
  1063. Prefetch("tags", TaggedItem.objects.filter(tag="django")),
  1064. ).get()
  1065. with self.assertNumQueries(0):
  1066. self.assertEqual(list(bookmark.tags.all()), [django_tag])
  1067. # The custom queryset filters should be applied to the queryset
  1068. # instance returned by the manager.
  1069. self.assertEqual(list(bookmark.tags.all()), list(bookmark.tags.all().all()))
  1070. def test_deleted_GFK(self):
  1071. TaggedItem.objects.create(tag="awesome", content_object=self.book1)
  1072. TaggedItem.objects.create(tag="awesome", content_object=self.book2)
  1073. ct = ContentType.objects.get_for_model(Book)
  1074. book1_pk = self.book1.pk
  1075. self.book1.delete()
  1076. with self.assertNumQueries(2):
  1077. qs = TaggedItem.objects.filter(tag="awesome").prefetch_related(
  1078. "content_object"
  1079. )
  1080. result = [
  1081. (tag.object_id, tag.content_type_id, tag.content_object) for tag in qs
  1082. ]
  1083. self.assertEqual(
  1084. result,
  1085. [
  1086. (book1_pk, ct.pk, None),
  1087. (self.book2.pk, ct.pk, self.book2),
  1088. ],
  1089. )
  1090. class MultiTableInheritanceTest(TestCase):
  1091. @classmethod
  1092. def setUpTestData(cls):
  1093. cls.book1 = BookWithYear.objects.create(title="Poems", published_year=2010)
  1094. cls.book2 = BookWithYear.objects.create(title="More poems", published_year=2011)
  1095. cls.author1 = AuthorWithAge.objects.create(
  1096. name="Jane", first_book=cls.book1, age=50
  1097. )
  1098. cls.author2 = AuthorWithAge.objects.create(
  1099. name="Tom", first_book=cls.book1, age=49
  1100. )
  1101. cls.author3 = AuthorWithAge.objects.create(
  1102. name="Robert", first_book=cls.book2, age=48
  1103. )
  1104. cls.author_address = AuthorAddress.objects.create(
  1105. author=cls.author1, address="SomeStreet 1"
  1106. )
  1107. cls.book2.aged_authors.add(cls.author2, cls.author3)
  1108. cls.br1 = BookReview.objects.create(book=cls.book1, notes="review book1")
  1109. cls.br2 = BookReview.objects.create(book=cls.book2, notes="review book2")
  1110. def test_foreignkey(self):
  1111. with self.assertNumQueries(2):
  1112. qs = AuthorWithAge.objects.prefetch_related("addresses")
  1113. addresses = [
  1114. [str(address) for address in obj.addresses.all()] for obj in qs
  1115. ]
  1116. self.assertEqual(addresses, [[str(self.author_address)], [], []])
  1117. def test_foreignkey_to_inherited(self):
  1118. with self.assertNumQueries(2):
  1119. qs = BookReview.objects.prefetch_related("book")
  1120. titles = [obj.book.title for obj in qs]
  1121. self.assertCountEqual(titles, ["Poems", "More poems"])
  1122. def test_m2m_to_inheriting_model(self):
  1123. qs = AuthorWithAge.objects.prefetch_related("books_with_year")
  1124. with self.assertNumQueries(2):
  1125. lst = [
  1126. [str(book) for book in author.books_with_year.all()] for author in qs
  1127. ]
  1128. qs = AuthorWithAge.objects.all()
  1129. lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs]
  1130. self.assertEqual(lst, lst2)
  1131. qs = BookWithYear.objects.prefetch_related("aged_authors")
  1132. with self.assertNumQueries(2):
  1133. lst = [[str(author) for author in book.aged_authors.all()] for book in qs]
  1134. qs = BookWithYear.objects.all()
  1135. lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs]
  1136. self.assertEqual(lst, lst2)
  1137. def test_parent_link_prefetch(self):
  1138. with self.assertNumQueries(2):
  1139. [a.author for a in AuthorWithAge.objects.prefetch_related("author")]
  1140. @override_settings(DEBUG=True)
  1141. def test_child_link_prefetch(self):
  1142. with self.assertNumQueries(2):
  1143. authors = [
  1144. a.authorwithage
  1145. for a in Author.objects.prefetch_related("authorwithage")
  1146. ]
  1147. # Regression for #18090: the prefetching query must include an IN clause.
  1148. # Note that on Oracle the table name is upper case in the generated SQL,
  1149. # thus the .lower() call.
  1150. self.assertIn("authorwithage", connection.queries[-1]["sql"].lower())
  1151. self.assertIn(" IN ", connection.queries[-1]["sql"])
  1152. self.assertEqual(authors, [a.authorwithage for a in Author.objects.all()])
  1153. class ForeignKeyToFieldTest(TestCase):
  1154. @classmethod
  1155. def setUpTestData(cls):
  1156. cls.book = Book.objects.create(title="Poems")
  1157. cls.author1 = Author.objects.create(name="Jane", first_book=cls.book)
  1158. cls.author2 = Author.objects.create(name="Tom", first_book=cls.book)
  1159. cls.author3 = Author.objects.create(name="Robert", first_book=cls.book)
  1160. cls.author_address = AuthorAddress.objects.create(
  1161. author=cls.author1, address="SomeStreet 1"
  1162. )
  1163. FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
  1164. FavoriteAuthors.objects.create(author=cls.author2, likes_author=cls.author3)
  1165. FavoriteAuthors.objects.create(author=cls.author3, likes_author=cls.author1)
  1166. def test_foreignkey(self):
  1167. with self.assertNumQueries(2):
  1168. qs = Author.objects.prefetch_related("addresses")
  1169. addresses = [
  1170. [str(address) for address in obj.addresses.all()] for obj in qs
  1171. ]
  1172. self.assertEqual(addresses, [[str(self.author_address)], [], []])
  1173. def test_m2m(self):
  1174. with self.assertNumQueries(3):
  1175. qs = Author.objects.prefetch_related("favorite_authors", "favors_me")
  1176. favorites = [
  1177. (
  1178. [str(i_like) for i_like in author.favorite_authors.all()],
  1179. [str(likes_me) for likes_me in author.favors_me.all()],
  1180. )
  1181. for author in qs
  1182. ]
  1183. self.assertEqual(
  1184. favorites,
  1185. [
  1186. ([str(self.author2)], [str(self.author3)]),
  1187. ([str(self.author3)], [str(self.author1)]),
  1188. ([str(self.author1)], [str(self.author2)]),
  1189. ],
  1190. )
  1191. class LookupOrderingTest(TestCase):
  1192. """
  1193. Test cases that demonstrate that ordering of lookups is important, and
  1194. ensure it is preserved.
  1195. """
  1196. @classmethod
  1197. def setUpTestData(cls):
  1198. person1 = Person.objects.create(name="Joe")
  1199. person2 = Person.objects.create(name="Mary")
  1200. # Set main_room for each house before creating the next one for
  1201. # databases where supports_nullable_unique_constraints is False.
  1202. house1 = House.objects.create(address="123 Main St")
  1203. room1_1 = Room.objects.create(name="Dining room", house=house1)
  1204. Room.objects.create(name="Lounge", house=house1)
  1205. Room.objects.create(name="Kitchen", house=house1)
  1206. house1.main_room = room1_1
  1207. house1.save()
  1208. person1.houses.add(house1)
  1209. house2 = House.objects.create(address="45 Side St")
  1210. room2_1 = Room.objects.create(name="Dining room", house=house2)
  1211. Room.objects.create(name="Lounge", house=house2)
  1212. house2.main_room = room2_1
  1213. house2.save()
  1214. person1.houses.add(house2)
  1215. house3 = House.objects.create(address="6 Downing St")
  1216. room3_1 = Room.objects.create(name="Dining room", house=house3)
  1217. Room.objects.create(name="Lounge", house=house3)
  1218. Room.objects.create(name="Kitchen", house=house3)
  1219. house3.main_room = room3_1
  1220. house3.save()
  1221. person2.houses.add(house3)
  1222. house4 = House.objects.create(address="7 Regents St")
  1223. room4_1 = Room.objects.create(name="Dining room", house=house4)
  1224. Room.objects.create(name="Lounge", house=house4)
  1225. house4.main_room = room4_1
  1226. house4.save()
  1227. person2.houses.add(house4)
  1228. def test_order(self):
  1229. with self.assertNumQueries(4):
  1230. # The following two queries must be done in the same order as written,
  1231. # otherwise 'primary_house' will cause non-prefetched lookups
  1232. qs = Person.objects.prefetch_related(
  1233. "houses__rooms", "primary_house__occupants"
  1234. )
  1235. [list(p.primary_house.occupants.all()) for p in qs]
  1236. class NullableTest(TestCase):
  1237. @classmethod
  1238. def setUpTestData(cls):
  1239. boss = Employee.objects.create(name="Peter")
  1240. Employee.objects.create(name="Joe", boss=boss)
  1241. Employee.objects.create(name="Angela", boss=boss)
  1242. def test_traverse_nullable(self):
  1243. # Because we use select_related() for 'boss', it doesn't need to be
  1244. # prefetched, but we can still traverse it although it contains some nulls
  1245. with self.assertNumQueries(2):
  1246. qs = Employee.objects.select_related("boss").prefetch_related("boss__serfs")
  1247. co_serfs = [
  1248. list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs
  1249. ]
  1250. qs2 = Employee.objects.select_related("boss")
  1251. co_serfs2 = [
  1252. list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2
  1253. ]
  1254. self.assertEqual(co_serfs, co_serfs2)
  1255. def test_prefetch_nullable(self):
  1256. # One for main employee, one for boss, one for serfs
  1257. with self.assertNumQueries(3):
  1258. qs = Employee.objects.prefetch_related("boss__serfs")
  1259. co_serfs = [
  1260. list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs
  1261. ]
  1262. qs2 = Employee.objects.all()
  1263. co_serfs2 = [
  1264. list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2
  1265. ]
  1266. self.assertEqual(co_serfs, co_serfs2)
  1267. def test_in_bulk(self):
  1268. """
  1269. In-bulk does correctly prefetch objects by not using .iterator()
  1270. directly.
  1271. """
  1272. boss1 = Employee.objects.create(name="Peter")
  1273. boss2 = Employee.objects.create(name="Jack")
  1274. with self.assertNumQueries(2):
  1275. # Prefetch is done and it does not cause any errors.
  1276. bulk = Employee.objects.prefetch_related("serfs").in_bulk(
  1277. [boss1.pk, boss2.pk]
  1278. )
  1279. for b in bulk.values():
  1280. list(b.serfs.all())
  1281. class MultiDbTests(TestCase):
  1282. databases = {"default", "other"}
  1283. def test_using_is_honored_m2m(self):
  1284. B = Book.objects.using("other")
  1285. A = Author.objects.using("other")
  1286. book1 = B.create(title="Poems")
  1287. book2 = B.create(title="Jane Eyre")
  1288. book3 = B.create(title="Wuthering Heights")
  1289. book4 = B.create(title="Sense and Sensibility")
  1290. author1 = A.create(name="Charlotte", first_book=book1)
  1291. author2 = A.create(name="Anne", first_book=book1)
  1292. author3 = A.create(name="Emily", first_book=book1)
  1293. author4 = A.create(name="Jane", first_book=book4)
  1294. book1.authors.add(author1, author2, author3)
  1295. book2.authors.add(author1)
  1296. book3.authors.add(author3)
  1297. book4.authors.add(author4)
  1298. # Forward
  1299. qs1 = B.prefetch_related("authors")
  1300. with self.assertNumQueries(2, using="other"):
  1301. books = "".join(
  1302. "%s (%s)\n"
  1303. % (book.title, ", ".join(a.name for a in book.authors.all()))
  1304. for book in qs1
  1305. )
  1306. self.assertEqual(
  1307. books,
  1308. "Poems (Charlotte, Anne, Emily)\n"
  1309. "Jane Eyre (Charlotte)\n"
  1310. "Wuthering Heights (Emily)\n"
  1311. "Sense and Sensibility (Jane)\n",
  1312. )
  1313. # Reverse
  1314. qs2 = A.prefetch_related("books")
  1315. with self.assertNumQueries(2, using="other"):
  1316. authors = "".join(
  1317. "%s: %s\n"
  1318. % (author.name, ", ".join(b.title for b in author.books.all()))
  1319. for author in qs2
  1320. )
  1321. self.assertEqual(
  1322. authors,
  1323. "Charlotte: Poems, Jane Eyre\n"
  1324. "Anne: Poems\n"
  1325. "Emily: Poems, Wuthering Heights\n"
  1326. "Jane: Sense and Sensibility\n",
  1327. )
  1328. def test_using_is_honored_fkey(self):
  1329. B = Book.objects.using("other")
  1330. A = Author.objects.using("other")
  1331. book1 = B.create(title="Poems")
  1332. book2 = B.create(title="Sense and Sensibility")
  1333. A.create(name="Charlotte Bronte", first_book=book1)
  1334. A.create(name="Jane Austen", first_book=book2)
  1335. # Forward
  1336. with self.assertNumQueries(2, using="other"):
  1337. books = ", ".join(
  1338. a.first_book.title for a in A.prefetch_related("first_book")
  1339. )
  1340. self.assertEqual("Poems, Sense and Sensibility", books)
  1341. # Reverse
  1342. with self.assertNumQueries(2, using="other"):
  1343. books = "".join(
  1344. "%s (%s)\n"
  1345. % (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1346. for b in B.prefetch_related("first_time_authors")
  1347. )
  1348. self.assertEqual(
  1349. books,
  1350. "Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
  1351. )
  1352. def test_using_is_honored_inheritance(self):
  1353. B = BookWithYear.objects.using("other")
  1354. A = AuthorWithAge.objects.using("other")
  1355. book1 = B.create(title="Poems", published_year=2010)
  1356. B.create(title="More poems", published_year=2011)
  1357. A.create(name="Jane", first_book=book1, age=50)
  1358. A.create(name="Tom", first_book=book1, age=49)
  1359. # parent link
  1360. with self.assertNumQueries(2, using="other"):
  1361. authors = ", ".join(a.author.name for a in A.prefetch_related("author"))
  1362. self.assertEqual(authors, "Jane, Tom")
  1363. # child link
  1364. with self.assertNumQueries(2, using="other"):
  1365. ages = ", ".join(
  1366. str(a.authorwithage.age) for a in A.prefetch_related("authorwithage")
  1367. )
  1368. self.assertEqual(ages, "50, 49")
  1369. def test_using_is_honored_custom_qs(self):
  1370. B = Book.objects.using("other")
  1371. A = Author.objects.using("other")
  1372. book1 = B.create(title="Poems")
  1373. book2 = B.create(title="Sense and Sensibility")
  1374. A.create(name="Charlotte Bronte", first_book=book1)
  1375. A.create(name="Jane Austen", first_book=book2)
  1376. # Implicit hinting
  1377. with self.assertNumQueries(2, using="other"):
  1378. prefetch = Prefetch("first_time_authors", queryset=Author.objects.all())
  1379. books = "".join(
  1380. "%s (%s)\n"
  1381. % (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1382. for b in B.prefetch_related(prefetch)
  1383. )
  1384. self.assertEqual(
  1385. books,
  1386. "Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
  1387. )
  1388. # Explicit using on the same db.
  1389. with self.assertNumQueries(2, using="other"):
  1390. prefetch = Prefetch(
  1391. "first_time_authors", queryset=Author.objects.using("other")
  1392. )
  1393. books = "".join(
  1394. "%s (%s)\n"
  1395. % (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1396. for b in B.prefetch_related(prefetch)
  1397. )
  1398. self.assertEqual(
  1399. books,
  1400. "Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
  1401. )
  1402. # Explicit using on a different db.
  1403. with self.assertNumQueries(1, using="default"), self.assertNumQueries(
  1404. 1, using="other"
  1405. ):
  1406. prefetch = Prefetch(
  1407. "first_time_authors", queryset=Author.objects.using("default")
  1408. )
  1409. books = "".join(
  1410. "%s (%s)\n"
  1411. % (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1412. for b in B.prefetch_related(prefetch)
  1413. )
  1414. self.assertEqual(books, "Poems ()\n" "Sense and Sensibility ()\n")
  1415. class Ticket19607Tests(TestCase):
  1416. @classmethod
  1417. def setUpTestData(cls):
  1418. LessonEntry.objects.bulk_create(
  1419. LessonEntry(id=id_, name1=name1, name2=name2)
  1420. for id_, name1, name2 in [
  1421. (1, "einfach", "simple"),
  1422. (2, "schwierig", "difficult"),
  1423. ]
  1424. )
  1425. WordEntry.objects.bulk_create(
  1426. WordEntry(id=id_, lesson_entry_id=lesson_entry_id, name=name)
  1427. for id_, lesson_entry_id, name in [
  1428. (1, 1, "einfach"),
  1429. (2, 1, "simple"),
  1430. (3, 2, "schwierig"),
  1431. (4, 2, "difficult"),
  1432. ]
  1433. )
  1434. def test_bug(self):
  1435. list(
  1436. WordEntry.objects.prefetch_related(
  1437. "lesson_entry", "lesson_entry__wordentry_set"
  1438. )
  1439. )
  1440. class Ticket21410Tests(TestCase):
  1441. @classmethod
  1442. def setUpTestData(cls):
  1443. book1 = Book.objects.create(title="Poems")
  1444. book2 = Book.objects.create(title="Jane Eyre")
  1445. book3 = Book.objects.create(title="Wuthering Heights")
  1446. book4 = Book.objects.create(title="Sense and Sensibility")
  1447. author1 = Author2.objects.create(name="Charlotte", first_book=book1)
  1448. author2 = Author2.objects.create(name="Anne", first_book=book1)
  1449. author3 = Author2.objects.create(name="Emily", first_book=book1)
  1450. author4 = Author2.objects.create(name="Jane", first_book=book4)
  1451. author1.favorite_books.add(book1, book2, book3)
  1452. author2.favorite_books.add(book1)
  1453. author3.favorite_books.add(book2)
  1454. author4.favorite_books.add(book3)
  1455. def test_bug(self):
  1456. list(Author2.objects.prefetch_related("first_book", "favorite_books"))
  1457. class Ticket21760Tests(TestCase):
  1458. @classmethod
  1459. def setUpTestData(cls):
  1460. cls.rooms = []
  1461. for _ in range(3):
  1462. house = House.objects.create()
  1463. for _ in range(3):
  1464. cls.rooms.append(Room.objects.create(house=house))
  1465. # Set main_room for each house before creating the next one for
  1466. # databases where supports_nullable_unique_constraints is False.
  1467. house.main_room = cls.rooms[-3]
  1468. house.save()
  1469. def test_bug(self):
  1470. prefetcher = get_prefetcher(self.rooms[0], "house", "house")[0]
  1471. queryset = prefetcher.get_prefetch_queryset(list(Room.objects.all()))[0]
  1472. self.assertNotIn(" JOIN ", str(queryset.query))
  1473. class DirectPrefetchedObjectCacheReuseTests(TestCase):
  1474. """
  1475. prefetch_related() reuses objects fetched in _prefetched_objects_cache.
  1476. When objects are prefetched and not stored as an instance attribute (often
  1477. intermediary relationships), they are saved to the
  1478. _prefetched_objects_cache attribute. prefetch_related() takes
  1479. _prefetched_objects_cache into account when determining whether an object
  1480. has been fetched[1] and retrieves results from it when it is populated [2].
  1481. [1]: #25546 (duplicate queries on nested Prefetch)
  1482. [2]: #27554 (queryset evaluation fails with a mix of nested and flattened
  1483. prefetches)
  1484. """
  1485. @classmethod
  1486. def setUpTestData(cls):
  1487. cls.book1, cls.book2 = [
  1488. Book.objects.create(title="book1"),
  1489. Book.objects.create(title="book2"),
  1490. ]
  1491. cls.author11, cls.author12, cls.author21 = [
  1492. Author.objects.create(first_book=cls.book1, name="Author11"),
  1493. Author.objects.create(first_book=cls.book1, name="Author12"),
  1494. Author.objects.create(first_book=cls.book2, name="Author21"),
  1495. ]
  1496. cls.author1_address1, cls.author1_address2, cls.author2_address1 = [
  1497. AuthorAddress.objects.create(author=cls.author11, address="Happy place"),
  1498. AuthorAddress.objects.create(author=cls.author12, address="Haunted house"),
  1499. AuthorAddress.objects.create(author=cls.author21, address="Happy place"),
  1500. ]
  1501. cls.bookwithyear1 = BookWithYear.objects.create(
  1502. title="Poems", published_year=2010
  1503. )
  1504. cls.bookreview1 = BookReview.objects.create(book=cls.bookwithyear1)
  1505. def test_detect_is_fetched(self):
  1506. """
  1507. Nested prefetch_related() shouldn't trigger duplicate queries for the same
  1508. lookup.
  1509. """
  1510. with self.assertNumQueries(3):
  1511. books = Book.objects.filter(title__in=["book1", "book2"]).prefetch_related(
  1512. Prefetch(
  1513. "first_time_authors",
  1514. Author.objects.prefetch_related(
  1515. Prefetch(
  1516. "addresses",
  1517. AuthorAddress.objects.filter(address="Happy place"),
  1518. )
  1519. ),
  1520. ),
  1521. )
  1522. book1, book2 = list(books)
  1523. with self.assertNumQueries(0):
  1524. self.assertSequenceEqual(
  1525. book1.first_time_authors.all(), [self.author11, self.author12]
  1526. )
  1527. self.assertSequenceEqual(book2.first_time_authors.all(), [self.author21])
  1528. self.assertSequenceEqual(
  1529. book1.first_time_authors.all()[0].addresses.all(),
  1530. [self.author1_address1],
  1531. )
  1532. self.assertSequenceEqual(
  1533. book1.first_time_authors.all()[1].addresses.all(), []
  1534. )
  1535. self.assertSequenceEqual(
  1536. book2.first_time_authors.all()[0].addresses.all(),
  1537. [self.author2_address1],
  1538. )
  1539. self.assertEqual(
  1540. list(book1.first_time_authors.all()),
  1541. list(book1.first_time_authors.all().all()),
  1542. )
  1543. self.assertEqual(
  1544. list(book2.first_time_authors.all()),
  1545. list(book2.first_time_authors.all().all()),
  1546. )
  1547. self.assertEqual(
  1548. list(book1.first_time_authors.all()[0].addresses.all()),
  1549. list(book1.first_time_authors.all()[0].addresses.all().all()),
  1550. )
  1551. self.assertEqual(
  1552. list(book1.first_time_authors.all()[1].addresses.all()),
  1553. list(book1.first_time_authors.all()[1].addresses.all().all()),
  1554. )
  1555. self.assertEqual(
  1556. list(book2.first_time_authors.all()[0].addresses.all()),
  1557. list(book2.first_time_authors.all()[0].addresses.all().all()),
  1558. )
  1559. def test_detect_is_fetched_with_to_attr(self):
  1560. with self.assertNumQueries(3):
  1561. books = Book.objects.filter(title__in=["book1", "book2"]).prefetch_related(
  1562. Prefetch(
  1563. "first_time_authors",
  1564. Author.objects.prefetch_related(
  1565. Prefetch(
  1566. "addresses",
  1567. AuthorAddress.objects.filter(address="Happy place"),
  1568. to_attr="happy_place",
  1569. )
  1570. ),
  1571. to_attr="first_authors",
  1572. ),
  1573. )
  1574. book1, book2 = list(books)
  1575. with self.assertNumQueries(0):
  1576. self.assertEqual(book1.first_authors, [self.author11, self.author12])
  1577. self.assertEqual(book2.first_authors, [self.author21])
  1578. self.assertEqual(
  1579. book1.first_authors[0].happy_place, [self.author1_address1]
  1580. )
  1581. self.assertEqual(book1.first_authors[1].happy_place, [])
  1582. self.assertEqual(
  1583. book2.first_authors[0].happy_place, [self.author2_address1]
  1584. )
  1585. def test_prefetch_reverse_foreign_key(self):
  1586. with self.assertNumQueries(2):
  1587. (bookwithyear1,) = BookWithYear.objects.prefetch_related("bookreview_set")
  1588. with self.assertNumQueries(0):
  1589. self.assertCountEqual(
  1590. bookwithyear1.bookreview_set.all(), [self.bookreview1]
  1591. )
  1592. with self.assertNumQueries(0):
  1593. prefetch_related_objects([bookwithyear1], "bookreview_set")
  1594. def test_add_clears_prefetched_objects(self):
  1595. bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
  1596. prefetch_related_objects([bookwithyear], "bookreview_set")
  1597. self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
  1598. new_review = BookReview.objects.create()
  1599. bookwithyear.bookreview_set.add(new_review)
  1600. self.assertCountEqual(
  1601. bookwithyear.bookreview_set.all(), [self.bookreview1, new_review]
  1602. )
  1603. def test_remove_clears_prefetched_objects(self):
  1604. bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
  1605. prefetch_related_objects([bookwithyear], "bookreview_set")
  1606. self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
  1607. bookwithyear.bookreview_set.remove(self.bookreview1)
  1608. self.assertCountEqual(bookwithyear.bookreview_set.all(), [])
  1609. class ReadPrefetchedObjectsCacheTests(TestCase):
  1610. @classmethod
  1611. def setUpTestData(cls):
  1612. cls.book1 = Book.objects.create(title="Les confessions Volume I")
  1613. cls.book2 = Book.objects.create(title="Candide")
  1614. cls.author1 = AuthorWithAge.objects.create(
  1615. name="Rousseau", first_book=cls.book1, age=70
  1616. )
  1617. cls.author2 = AuthorWithAge.objects.create(
  1618. name="Voltaire", first_book=cls.book2, age=65
  1619. )
  1620. cls.book1.authors.add(cls.author1)
  1621. cls.book2.authors.add(cls.author2)
  1622. FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
  1623. def test_retrieves_results_from_prefetched_objects_cache(self):
  1624. """
  1625. When intermediary results are prefetched without a destination
  1626. attribute, they are saved in the RelatedManager's cache
  1627. (_prefetched_objects_cache). prefetch_related() uses this cache
  1628. (#27554).
  1629. """
  1630. authors = AuthorWithAge.objects.prefetch_related(
  1631. Prefetch(
  1632. "author",
  1633. queryset=Author.objects.prefetch_related(
  1634. # Results are saved in the RelatedManager's cache
  1635. # (_prefetched_objects_cache) and do not replace the
  1636. # RelatedManager on Author instances (favorite_authors)
  1637. Prefetch("favorite_authors__first_book"),
  1638. ),
  1639. ),
  1640. )
  1641. with self.assertNumQueries(4):
  1642. # AuthorWithAge -> Author -> FavoriteAuthors, Book
  1643. self.assertSequenceEqual(authors, [self.author1, self.author2])
  1644. class NestedPrefetchTests(TestCase):
  1645. @classmethod
  1646. def setUpTestData(cls):
  1647. house = House.objects.create(name="Big house", address="123 Main St")
  1648. cls.room = Room.objects.create(name="Kitchen", house=house)
  1649. def test_nested_prefetch_is_not_overwritten_by_related_object(self):
  1650. """
  1651. The prefetched relationship is used rather than populating the reverse
  1652. relationship from the parent, when prefetching a set of child objects
  1653. related to a set of parent objects and the child queryset itself
  1654. specifies a prefetch back to the parent.
  1655. """
  1656. queryset = House.objects.only("name").prefetch_related(
  1657. Prefetch(
  1658. "rooms",
  1659. queryset=Room.objects.prefetch_related(
  1660. Prefetch("house", queryset=House.objects.only("address")),
  1661. ),
  1662. ),
  1663. )
  1664. with self.assertNumQueries(3):
  1665. house = queryset.first()
  1666. self.assertIs(Room.house.is_cached(self.room), True)
  1667. with self.assertNumQueries(0):
  1668. house.rooms.first().house.address
  1669. class PrefetchLimitTests(TestDataMixin, TestCase):
  1670. @skipUnlessDBFeature("supports_over_clause")
  1671. def test_m2m_forward(self):
  1672. authors = Author.objects.all() # Meta.ordering
  1673. with self.assertNumQueries(3):
  1674. books = list(
  1675. Book.objects.prefetch_related(
  1676. Prefetch("authors", authors),
  1677. Prefetch("authors", authors[1:], to_attr="authors_sliced"),
  1678. )
  1679. )
  1680. for book in books:
  1681. with self.subTest(book=book):
  1682. self.assertEqual(book.authors_sliced, list(book.authors.all())[1:])
  1683. @skipUnlessDBFeature("supports_over_clause")
  1684. def test_m2m_reverse(self):
  1685. books = Book.objects.order_by("title")
  1686. with self.assertNumQueries(3):
  1687. authors = list(
  1688. Author.objects.prefetch_related(
  1689. Prefetch("books", books),
  1690. Prefetch("books", books[1:2], to_attr="books_sliced"),
  1691. )
  1692. )
  1693. for author in authors:
  1694. with self.subTest(author=author):
  1695. self.assertEqual(author.books_sliced, list(author.books.all())[1:2])
  1696. @skipUnlessDBFeature("supports_over_clause")
  1697. def test_foreignkey_reverse(self):
  1698. authors = Author.objects.order_by("-name")
  1699. with self.assertNumQueries(3):
  1700. books = list(
  1701. Book.objects.prefetch_related(
  1702. Prefetch(
  1703. "first_time_authors",
  1704. authors,
  1705. ),
  1706. Prefetch(
  1707. "first_time_authors",
  1708. authors[1:],
  1709. to_attr="first_time_authors_sliced",
  1710. ),
  1711. )
  1712. )
  1713. for book in books:
  1714. with self.subTest(book=book):
  1715. self.assertEqual(
  1716. book.first_time_authors_sliced,
  1717. list(book.first_time_authors.all())[1:],
  1718. )
  1719. @skipUnlessDBFeature("supports_over_clause")
  1720. def test_reverse_ordering(self):
  1721. authors = Author.objects.reverse() # Reverse Meta.ordering
  1722. with self.assertNumQueries(3):
  1723. books = list(
  1724. Book.objects.prefetch_related(
  1725. Prefetch("authors", authors),
  1726. Prefetch("authors", authors[1:], to_attr="authors_sliced"),
  1727. )
  1728. )
  1729. for book in books:
  1730. with self.subTest(book=book):
  1731. self.assertEqual(book.authors_sliced, list(book.authors.all())[1:])
  1732. @skipIfDBFeature("supports_over_clause")
  1733. def test_window_not_supported(self):
  1734. authors = Author.objects.all()
  1735. msg = (
  1736. "Prefetching from a limited queryset is only supported on backends that "
  1737. "support window functions."
  1738. )
  1739. with self.assertRaisesMessage(NotSupportedError, msg):
  1740. list(Book.objects.prefetch_related(Prefetch("authors", authors[1:])))