tests.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. from django.contrib.contenttypes.models import ContentType
  2. from django.core.exceptions import ObjectDoesNotExist
  3. from django.db import connection
  4. from django.db.models import Prefetch, QuerySet
  5. from django.db.models.query import get_prefetcher, prefetch_related_objects
  6. from django.test import TestCase, override_settings
  7. from django.test.utils import CaptureQueriesContext
  8. from .models import (
  9. Author, Author2, AuthorAddress, AuthorWithAge, Bio, Book, Bookmark,
  10. BookReview, BookWithYear, Comment, Department, Employee, FavoriteAuthors,
  11. House, LessonEntry, ModelIterableSubclass, Person, Qualification, Reader,
  12. Room, TaggedItem, Teacher, WordEntry,
  13. )
  14. class TestDataMixin:
  15. @classmethod
  16. def setUpTestData(cls):
  17. cls.book1 = Book.objects.create(title='Poems')
  18. cls.book2 = Book.objects.create(title='Jane Eyre')
  19. cls.book3 = Book.objects.create(title='Wuthering Heights')
  20. cls.book4 = Book.objects.create(title='Sense and Sensibility')
  21. cls.author1 = Author.objects.create(name='Charlotte', first_book=cls.book1)
  22. cls.author2 = Author.objects.create(name='Anne', first_book=cls.book1)
  23. cls.author3 = Author.objects.create(name='Emily', first_book=cls.book1)
  24. cls.author4 = Author.objects.create(name='Jane', first_book=cls.book4)
  25. cls.book1.authors.add(cls.author1, cls.author2, cls.author3)
  26. cls.book2.authors.add(cls.author1)
  27. cls.book3.authors.add(cls.author3)
  28. cls.book4.authors.add(cls.author4)
  29. cls.reader1 = Reader.objects.create(name='Amy')
  30. cls.reader2 = Reader.objects.create(name='Belinda')
  31. cls.reader1.books_read.add(cls.book1, cls.book4)
  32. cls.reader2.books_read.add(cls.book2, cls.book4)
  33. class PrefetchRelatedTests(TestDataMixin, TestCase):
  34. def assertWhereContains(self, sql, needle):
  35. where_idx = sql.index('WHERE')
  36. self.assertEqual(
  37. sql.count(str(needle), where_idx), 1,
  38. msg="WHERE clause doesn't contain %s, actual SQL: %s" % (needle, sql[where_idx:])
  39. )
  40. def test_m2m_forward(self):
  41. with self.assertNumQueries(2):
  42. lists = [list(b.authors.all()) for b in Book.objects.prefetch_related('authors')]
  43. normal_lists = [list(b.authors.all()) for b in Book.objects.all()]
  44. self.assertEqual(lists, normal_lists)
  45. def test_m2m_reverse(self):
  46. with self.assertNumQueries(2):
  47. lists = [list(a.books.all()) for a in Author.objects.prefetch_related('books')]
  48. normal_lists = [list(a.books.all()) for a in Author.objects.all()]
  49. self.assertEqual(lists, normal_lists)
  50. def test_foreignkey_forward(self):
  51. with self.assertNumQueries(2):
  52. books = [a.first_book for a in Author.objects.prefetch_related('first_book')]
  53. normal_books = [a.first_book for a in Author.objects.all()]
  54. self.assertEqual(books, normal_books)
  55. def test_foreignkey_reverse(self):
  56. with self.assertNumQueries(2):
  57. [list(b.first_time_authors.all())
  58. for b in Book.objects.prefetch_related('first_time_authors')]
  59. self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"])
  60. def test_onetoone_reverse_no_match(self):
  61. # Regression for #17439
  62. with self.assertNumQueries(2):
  63. book = Book.objects.prefetch_related('bookwithyear').all()[0]
  64. with self.assertNumQueries(0):
  65. with self.assertRaises(BookWithYear.DoesNotExist):
  66. book.bookwithyear
  67. def test_onetoone_reverse_with_to_field_pk(self):
  68. """
  69. A model (Bio) with a OneToOneField primary key (author) that references
  70. a non-pk field (name) on the related model (Author) is prefetchable.
  71. """
  72. Bio.objects.bulk_create([
  73. Bio(author=self.author1),
  74. Bio(author=self.author2),
  75. Bio(author=self.author3),
  76. ])
  77. authors = Author.objects.filter(
  78. name__in=[self.author1, self.author2, self.author3],
  79. ).prefetch_related('bio')
  80. with self.assertNumQueries(2):
  81. for author in authors:
  82. self.assertEqual(author.name, author.bio.author.name)
  83. def test_survives_clone(self):
  84. with self.assertNumQueries(2):
  85. [list(b.first_time_authors.all())
  86. for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)]
  87. def test_len(self):
  88. with self.assertNumQueries(2):
  89. qs = Book.objects.prefetch_related('first_time_authors')
  90. len(qs)
  91. [list(b.first_time_authors.all()) for b in qs]
  92. def test_bool(self):
  93. with self.assertNumQueries(2):
  94. qs = Book.objects.prefetch_related('first_time_authors')
  95. bool(qs)
  96. [list(b.first_time_authors.all()) for b in qs]
  97. def test_count(self):
  98. with self.assertNumQueries(2):
  99. qs = Book.objects.prefetch_related('first_time_authors')
  100. [b.first_time_authors.count() for b in qs]
  101. def test_exists(self):
  102. with self.assertNumQueries(2):
  103. qs = Book.objects.prefetch_related('first_time_authors')
  104. [b.first_time_authors.exists() for b in qs]
  105. def test_in_and_prefetch_related(self):
  106. """
  107. Regression test for #20242 - QuerySet "in" didn't work the first time
  108. when using prefetch_related. This was fixed by the removal of chunked
  109. reads from QuerySet iteration in
  110. 70679243d1786e03557c28929f9762a119e3ac14.
  111. """
  112. qs = Book.objects.prefetch_related('first_time_authors')
  113. self.assertIn(qs[0], qs)
  114. def test_clear(self):
  115. with self.assertNumQueries(5):
  116. with_prefetch = Author.objects.prefetch_related('books')
  117. without_prefetch = with_prefetch.prefetch_related(None)
  118. [list(a.books.all()) for a in without_prefetch]
  119. def test_m2m_then_m2m(self):
  120. """A m2m can be followed through another m2m."""
  121. with self.assertNumQueries(3):
  122. qs = Author.objects.prefetch_related('books__read_by')
  123. lists = [[[str(r) for r in b.read_by.all()]
  124. for b in a.books.all()]
  125. for a in qs]
  126. self.assertEqual(lists, [
  127. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  128. [["Amy"]], # Anne - Poems
  129. [["Amy"], []], # Emily - Poems, Wuthering Heights
  130. [["Amy", "Belinda"]], # Jane - Sense and Sense
  131. ])
  132. def test_overriding_prefetch(self):
  133. with self.assertNumQueries(3):
  134. qs = Author.objects.prefetch_related('books', 'books__read_by')
  135. lists = [[[str(r) for r in b.read_by.all()]
  136. for b in a.books.all()]
  137. for a in qs]
  138. self.assertEqual(lists, [
  139. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  140. [["Amy"]], # Anne - Poems
  141. [["Amy"], []], # Emily - Poems, Wuthering Heights
  142. [["Amy", "Belinda"]], # Jane - Sense and Sense
  143. ])
  144. with self.assertNumQueries(3):
  145. qs = Author.objects.prefetch_related('books__read_by', 'books')
  146. lists = [[[str(r) for r in b.read_by.all()]
  147. for b in a.books.all()]
  148. for a in qs]
  149. self.assertEqual(lists, [
  150. [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
  151. [["Amy"]], # Anne - Poems
  152. [["Amy"], []], # Emily - Poems, Wuthering Heights
  153. [["Amy", "Belinda"]], # Jane - Sense and Sense
  154. ])
  155. def test_get(self):
  156. """
  157. Objects retrieved with .get() get the prefetch behavior.
  158. """
  159. # Need a double
  160. with self.assertNumQueries(3):
  161. author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte")
  162. lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()]
  163. self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
  164. def test_foreign_key_then_m2m(self):
  165. """
  166. A m2m relation can be followed after a relation like ForeignKey that
  167. doesn't have many objects.
  168. """
  169. with self.assertNumQueries(2):
  170. qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
  171. lists = [[str(r) for r in a.first_book.read_by.all()]
  172. for a in qs]
  173. self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
  174. def test_reverse_one_to_one_then_m2m(self):
  175. """
  176. A m2m relation can be followed afterr going through the select_related
  177. reverse of an o2o.
  178. """
  179. qs = Author.objects.prefetch_related('bio__books').select_related('bio')
  180. with self.assertNumQueries(1):
  181. list(qs.all())
  182. Bio.objects.create(author=self.author1)
  183. with self.assertNumQueries(2):
  184. list(qs.all())
  185. def test_attribute_error(self):
  186. qs = Reader.objects.all().prefetch_related('books_read__xyz')
  187. msg = (
  188. "Cannot find 'xyz' on Book object, 'books_read__xyz' "
  189. "is an invalid parameter to prefetch_related()"
  190. )
  191. with self.assertRaisesMessage(AttributeError, msg) as cm:
  192. list(qs)
  193. self.assertIn('prefetch_related', str(cm.exception))
  194. def test_invalid_final_lookup(self):
  195. qs = Book.objects.prefetch_related('authors__name')
  196. msg = (
  197. "'authors__name' does not resolve to an item that supports "
  198. "prefetching - this is an invalid parameter to prefetch_related()."
  199. )
  200. with self.assertRaisesMessage(ValueError, msg) as cm:
  201. list(qs)
  202. self.assertIn('prefetch_related', str(cm.exception))
  203. self.assertIn("name", str(cm.exception))
  204. def test_forward_m2m_to_attr_conflict(self):
  205. msg = 'to_attr=authors conflicts with a field on the Book model.'
  206. authors = Author.objects.all()
  207. with self.assertRaisesMessage(ValueError, msg):
  208. list(Book.objects.prefetch_related(
  209. Prefetch('authors', queryset=authors, to_attr='authors'),
  210. ))
  211. # Without the ValueError, an author was deleted due to the implicit
  212. # save of the relation assignment.
  213. self.assertEqual(self.book1.authors.count(), 3)
  214. def test_reverse_m2m_to_attr_conflict(self):
  215. msg = 'to_attr=books conflicts with a field on the Author model.'
  216. poems = Book.objects.filter(title='Poems')
  217. with self.assertRaisesMessage(ValueError, msg):
  218. list(Author.objects.prefetch_related(
  219. Prefetch('books', queryset=poems, to_attr='books'),
  220. ))
  221. # Without the ValueError, a book was deleted due to the implicit
  222. # save of reverse relation assignment.
  223. self.assertEqual(self.author1.books.count(), 2)
  224. def test_m2m_then_reverse_fk_object_ids(self):
  225. with CaptureQueriesContext(connection) as queries:
  226. list(Book.objects.prefetch_related('authors__addresses'))
  227. sql = queries[-1]['sql']
  228. self.assertWhereContains(sql, self.author1.name)
  229. def test_m2m_then_m2m_object_ids(self):
  230. with CaptureQueriesContext(connection) as queries:
  231. list(Book.objects.prefetch_related('authors__favorite_authors'))
  232. sql = queries[-1]['sql']
  233. self.assertWhereContains(sql, self.author1.name)
  234. def test_m2m_then_reverse_one_to_one_object_ids(self):
  235. with CaptureQueriesContext(connection) as queries:
  236. list(Book.objects.prefetch_related('authors__authorwithage'))
  237. sql = queries[-1]['sql']
  238. self.assertWhereContains(sql, self.author1.id)
  239. class RawQuerySetTests(TestDataMixin, TestCase):
  240. def test_basic(self):
  241. with self.assertNumQueries(2):
  242. books = Book.objects.raw(
  243. "SELECT * FROM prefetch_related_book WHERE id = %s",
  244. (self.book1.id,)
  245. ).prefetch_related('authors')
  246. book1 = list(books)[0]
  247. with self.assertNumQueries(0):
  248. self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3])
  249. def test_prefetch_before_raw(self):
  250. with self.assertNumQueries(2):
  251. books = Book.objects.prefetch_related('authors').raw(
  252. "SELECT * FROM prefetch_related_book WHERE id = %s",
  253. (self.book1.id,)
  254. )
  255. book1 = list(books)[0]
  256. with self.assertNumQueries(0):
  257. self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3])
  258. def test_clear(self):
  259. with self.assertNumQueries(5):
  260. with_prefetch = Author.objects.raw(
  261. "SELECT * FROM prefetch_related_author"
  262. ).prefetch_related('books')
  263. without_prefetch = with_prefetch.prefetch_related(None)
  264. [list(a.books.all()) for a in without_prefetch]
  265. class CustomPrefetchTests(TestCase):
  266. @classmethod
  267. def traverse_qs(cls, obj_iter, path):
  268. """
  269. Helper method that returns a list containing a list of the objects in the
  270. obj_iter. Then for each object in the obj_iter, the path will be
  271. recursively travelled and the found objects are added to the return value.
  272. """
  273. ret_val = []
  274. if hasattr(obj_iter, 'all'):
  275. obj_iter = obj_iter.all()
  276. try:
  277. iter(obj_iter)
  278. except TypeError:
  279. obj_iter = [obj_iter]
  280. for obj in obj_iter:
  281. rel_objs = []
  282. for part in path:
  283. if not part:
  284. continue
  285. try:
  286. related = getattr(obj, part[0])
  287. except ObjectDoesNotExist:
  288. continue
  289. if related is not None:
  290. rel_objs.extend(cls.traverse_qs(related, [part[1:]]))
  291. ret_val.append((obj, rel_objs))
  292. return ret_val
  293. @classmethod
  294. def setUpTestData(cls):
  295. cls.person1 = Person.objects.create(name='Joe')
  296. cls.person2 = Person.objects.create(name='Mary')
  297. # Set main_room for each house before creating the next one for
  298. # databases where supports_nullable_unique_constraints is False.
  299. cls.house1 = House.objects.create(name='House 1', address='123 Main St', owner=cls.person1)
  300. cls.room1_1 = Room.objects.create(name='Dining room', house=cls.house1)
  301. cls.room1_2 = Room.objects.create(name='Lounge', house=cls.house1)
  302. cls.room1_3 = Room.objects.create(name='Kitchen', house=cls.house1)
  303. cls.house1.main_room = cls.room1_1
  304. cls.house1.save()
  305. cls.person1.houses.add(cls.house1)
  306. cls.house2 = House.objects.create(name='House 2', address='45 Side St', owner=cls.person1)
  307. cls.room2_1 = Room.objects.create(name='Dining room', house=cls.house2)
  308. cls.room2_2 = Room.objects.create(name='Lounge', house=cls.house2)
  309. cls.room2_3 = Room.objects.create(name='Kitchen', house=cls.house2)
  310. cls.house2.main_room = cls.room2_1
  311. cls.house2.save()
  312. cls.person1.houses.add(cls.house2)
  313. cls.house3 = House.objects.create(name='House 3', address='6 Downing St', owner=cls.person2)
  314. cls.room3_1 = Room.objects.create(name='Dining room', house=cls.house3)
  315. cls.room3_2 = Room.objects.create(name='Lounge', house=cls.house3)
  316. cls.room3_3 = Room.objects.create(name='Kitchen', house=cls.house3)
  317. cls.house3.main_room = cls.room3_1
  318. cls.house3.save()
  319. cls.person2.houses.add(cls.house3)
  320. cls.house4 = House.objects.create(name='house 4', address="7 Regents St", owner=cls.person2)
  321. cls.room4_1 = Room.objects.create(name='Dining room', house=cls.house4)
  322. cls.room4_2 = Room.objects.create(name='Lounge', house=cls.house4)
  323. cls.room4_3 = Room.objects.create(name='Kitchen', house=cls.house4)
  324. cls.house4.main_room = cls.room4_1
  325. cls.house4.save()
  326. cls.person2.houses.add(cls.house4)
  327. def test_traverse_qs(self):
  328. qs = Person.objects.prefetch_related('houses')
  329. related_objs_normal = [list(p.houses.all()) for p in qs],
  330. related_objs_from_traverse = [[inner[0] for inner in o[1]]
  331. for o in self.traverse_qs(qs, [['houses']])]
  332. self.assertEqual(related_objs_normal, (related_objs_from_traverse,))
  333. def test_ambiguous(self):
  334. # Ambiguous: Lookup was already seen with a different queryset.
  335. msg = (
  336. "'houses' lookup was already seen with a different queryset. You "
  337. "may need to adjust the ordering of your lookups."
  338. )
  339. with self.assertRaisesMessage(ValueError, msg):
  340. self.traverse_qs(
  341. Person.objects.prefetch_related('houses__rooms', Prefetch('houses', queryset=House.objects.all())),
  342. [['houses', 'rooms']]
  343. )
  344. # Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms.
  345. msg = (
  346. "Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is "
  347. "an invalid parameter to prefetch_related()"
  348. )
  349. with self.assertRaisesMessage(AttributeError, msg):
  350. self.traverse_qs(
  351. Person.objects.prefetch_related(
  352. 'houses_lst__rooms',
  353. Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')
  354. ),
  355. [['houses', 'rooms']]
  356. )
  357. # Not ambiguous.
  358. self.traverse_qs(
  359. Person.objects.prefetch_related('houses__rooms', 'houses'),
  360. [['houses', 'rooms']]
  361. )
  362. self.traverse_qs(
  363. Person.objects.prefetch_related(
  364. 'houses__rooms',
  365. Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')
  366. ),
  367. [['houses', 'rooms']]
  368. )
  369. def test_m2m(self):
  370. # Control lookups.
  371. with self.assertNumQueries(2):
  372. lst1 = self.traverse_qs(
  373. Person.objects.prefetch_related('houses'),
  374. [['houses']]
  375. )
  376. # Test lookups.
  377. with self.assertNumQueries(2):
  378. lst2 = self.traverse_qs(
  379. Person.objects.prefetch_related(Prefetch('houses')),
  380. [['houses']]
  381. )
  382. self.assertEqual(lst1, lst2)
  383. with self.assertNumQueries(2):
  384. lst2 = self.traverse_qs(
  385. Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst')),
  386. [['houses_lst']]
  387. )
  388. self.assertEqual(lst1, lst2)
  389. def test_reverse_m2m(self):
  390. # Control lookups.
  391. with self.assertNumQueries(2):
  392. lst1 = self.traverse_qs(
  393. House.objects.prefetch_related('occupants'),
  394. [['occupants']]
  395. )
  396. # Test lookups.
  397. with self.assertNumQueries(2):
  398. lst2 = self.traverse_qs(
  399. House.objects.prefetch_related(Prefetch('occupants')),
  400. [['occupants']]
  401. )
  402. self.assertEqual(lst1, lst2)
  403. with self.assertNumQueries(2):
  404. lst2 = self.traverse_qs(
  405. House.objects.prefetch_related(Prefetch('occupants', to_attr='occupants_lst')),
  406. [['occupants_lst']]
  407. )
  408. self.assertEqual(lst1, lst2)
  409. def test_m2m_through_fk(self):
  410. # Control lookups.
  411. with self.assertNumQueries(3):
  412. lst1 = self.traverse_qs(
  413. Room.objects.prefetch_related('house__occupants'),
  414. [['house', 'occupants']]
  415. )
  416. # Test lookups.
  417. with self.assertNumQueries(3):
  418. lst2 = self.traverse_qs(
  419. Room.objects.prefetch_related(Prefetch('house__occupants')),
  420. [['house', 'occupants']]
  421. )
  422. self.assertEqual(lst1, lst2)
  423. with self.assertNumQueries(3):
  424. lst2 = self.traverse_qs(
  425. Room.objects.prefetch_related(Prefetch('house__occupants', to_attr='occupants_lst')),
  426. [['house', 'occupants_lst']]
  427. )
  428. self.assertEqual(lst1, lst2)
  429. def test_m2m_through_gfk(self):
  430. TaggedItem.objects.create(tag="houses", content_object=self.house1)
  431. TaggedItem.objects.create(tag="houses", content_object=self.house2)
  432. # Control lookups.
  433. with self.assertNumQueries(3):
  434. lst1 = self.traverse_qs(
  435. TaggedItem.objects.filter(tag='houses').prefetch_related('content_object__rooms'),
  436. [['content_object', 'rooms']]
  437. )
  438. # Test lookups.
  439. with self.assertNumQueries(3):
  440. lst2 = self.traverse_qs(
  441. TaggedItem.objects.prefetch_related(
  442. Prefetch('content_object'),
  443. Prefetch('content_object__rooms', to_attr='rooms_lst')
  444. ),
  445. [['content_object', 'rooms_lst']]
  446. )
  447. self.assertEqual(lst1, lst2)
  448. def test_o2m_through_m2m(self):
  449. # Control lookups.
  450. with self.assertNumQueries(3):
  451. lst1 = self.traverse_qs(
  452. Person.objects.prefetch_related('houses', 'houses__rooms'),
  453. [['houses', 'rooms']]
  454. )
  455. # Test lookups.
  456. with self.assertNumQueries(3):
  457. lst2 = self.traverse_qs(
  458. Person.objects.prefetch_related(Prefetch('houses'), 'houses__rooms'),
  459. [['houses', 'rooms']]
  460. )
  461. self.assertEqual(lst1, lst2)
  462. with self.assertNumQueries(3):
  463. lst2 = self.traverse_qs(
  464. Person.objects.prefetch_related(Prefetch('houses'), Prefetch('houses__rooms')),
  465. [['houses', 'rooms']]
  466. )
  467. self.assertEqual(lst1, lst2)
  468. with self.assertNumQueries(3):
  469. lst2 = self.traverse_qs(
  470. Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst'), 'houses_lst__rooms'),
  471. [['houses_lst', 'rooms']]
  472. )
  473. self.assertEqual(lst1, lst2)
  474. with self.assertNumQueries(3):
  475. lst2 = self.traverse_qs(
  476. Person.objects.prefetch_related(
  477. Prefetch('houses', to_attr='houses_lst'),
  478. Prefetch('houses_lst__rooms', to_attr='rooms_lst')
  479. ),
  480. [['houses_lst', 'rooms_lst']]
  481. )
  482. self.assertEqual(lst1, lst2)
  483. def test_generic_rel(self):
  484. bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
  485. TaggedItem.objects.create(content_object=bookmark, tag='django')
  486. TaggedItem.objects.create(content_object=bookmark, favorite=bookmark, tag='python')
  487. # Control lookups.
  488. with self.assertNumQueries(4):
  489. lst1 = self.traverse_qs(
  490. Bookmark.objects.prefetch_related('tags', 'tags__content_object', 'favorite_tags'),
  491. [['tags', 'content_object'], ['favorite_tags']]
  492. )
  493. # Test lookups.
  494. with self.assertNumQueries(4):
  495. lst2 = self.traverse_qs(
  496. Bookmark.objects.prefetch_related(
  497. Prefetch('tags', to_attr='tags_lst'),
  498. Prefetch('tags_lst__content_object'),
  499. Prefetch('favorite_tags'),
  500. ),
  501. [['tags_lst', 'content_object'], ['favorite_tags']]
  502. )
  503. self.assertEqual(lst1, lst2)
  504. def test_traverse_single_item_property(self):
  505. # Control lookups.
  506. with self.assertNumQueries(5):
  507. lst1 = self.traverse_qs(
  508. Person.objects.prefetch_related(
  509. 'houses__rooms',
  510. 'primary_house__occupants__houses',
  511. ),
  512. [['primary_house', 'occupants', 'houses']]
  513. )
  514. # Test lookups.
  515. with self.assertNumQueries(5):
  516. lst2 = self.traverse_qs(
  517. Person.objects.prefetch_related(
  518. 'houses__rooms',
  519. Prefetch('primary_house__occupants', to_attr='occupants_lst'),
  520. 'primary_house__occupants_lst__houses',
  521. ),
  522. [['primary_house', 'occupants_lst', 'houses']]
  523. )
  524. self.assertEqual(lst1, lst2)
  525. def test_traverse_multiple_items_property(self):
  526. # Control lookups.
  527. with self.assertNumQueries(4):
  528. lst1 = self.traverse_qs(
  529. Person.objects.prefetch_related(
  530. 'houses',
  531. 'all_houses__occupants__houses',
  532. ),
  533. [['all_houses', 'occupants', 'houses']]
  534. )
  535. # Test lookups.
  536. with self.assertNumQueries(4):
  537. lst2 = self.traverse_qs(
  538. Person.objects.prefetch_related(
  539. 'houses',
  540. Prefetch('all_houses__occupants', to_attr='occupants_lst'),
  541. 'all_houses__occupants_lst__houses',
  542. ),
  543. [['all_houses', 'occupants_lst', 'houses']]
  544. )
  545. self.assertEqual(lst1, lst2)
  546. def test_custom_qs(self):
  547. # Test basic.
  548. with self.assertNumQueries(2):
  549. lst1 = list(Person.objects.prefetch_related('houses'))
  550. with self.assertNumQueries(2):
  551. lst2 = list(Person.objects.prefetch_related(
  552. Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')))
  553. self.assertEqual(
  554. self.traverse_qs(lst1, [['houses']]),
  555. self.traverse_qs(lst2, [['houses_lst']])
  556. )
  557. # Test queryset filtering.
  558. with self.assertNumQueries(2):
  559. lst2 = list(
  560. Person.objects.prefetch_related(
  561. Prefetch(
  562. 'houses',
  563. queryset=House.objects.filter(pk__in=[self.house1.pk, self.house3.pk]),
  564. to_attr='houses_lst',
  565. )
  566. )
  567. )
  568. self.assertEqual(len(lst2[0].houses_lst), 1)
  569. self.assertEqual(lst2[0].houses_lst[0], self.house1)
  570. self.assertEqual(len(lst2[1].houses_lst), 1)
  571. self.assertEqual(lst2[1].houses_lst[0], self.house3)
  572. # Test flattened.
  573. with self.assertNumQueries(3):
  574. lst1 = list(Person.objects.prefetch_related('houses__rooms'))
  575. with self.assertNumQueries(3):
  576. lst2 = list(Person.objects.prefetch_related(
  577. Prefetch('houses__rooms', queryset=Room.objects.all(), to_attr='rooms_lst')))
  578. self.assertEqual(
  579. self.traverse_qs(lst1, [['houses', 'rooms']]),
  580. self.traverse_qs(lst2, [['houses', 'rooms_lst']])
  581. )
  582. # Test inner select_related.
  583. with self.assertNumQueries(3):
  584. lst1 = list(Person.objects.prefetch_related('houses__owner'))
  585. with self.assertNumQueries(2):
  586. lst2 = list(Person.objects.prefetch_related(
  587. Prefetch('houses', queryset=House.objects.select_related('owner'))))
  588. self.assertEqual(
  589. self.traverse_qs(lst1, [['houses', 'owner']]),
  590. self.traverse_qs(lst2, [['houses', 'owner']])
  591. )
  592. # Test inner prefetch.
  593. inner_rooms_qs = Room.objects.filter(pk__in=[self.room1_1.pk, self.room1_2.pk])
  594. houses_qs_prf = House.objects.prefetch_related(
  595. Prefetch('rooms', queryset=inner_rooms_qs, to_attr='rooms_lst'))
  596. with self.assertNumQueries(4):
  597. lst2 = list(Person.objects.prefetch_related(
  598. Prefetch('houses', queryset=houses_qs_prf.filter(pk=self.house1.pk), to_attr='houses_lst'),
  599. Prefetch('houses_lst__rooms_lst__main_room_of')
  600. ))
  601. self.assertEqual(len(lst2[0].houses_lst[0].rooms_lst), 2)
  602. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0], self.room1_1)
  603. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[1], self.room1_2)
  604. self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0].main_room_of, self.house1)
  605. self.assertEqual(len(lst2[1].houses_lst), 0)
  606. # Test ForwardManyToOneDescriptor.
  607. houses = House.objects.select_related('owner')
  608. with self.assertNumQueries(6):
  609. rooms = Room.objects.all().prefetch_related('house')
  610. lst1 = self.traverse_qs(rooms, [['house', 'owner']])
  611. with self.assertNumQueries(2):
  612. rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all()))
  613. lst2 = self.traverse_qs(rooms, [['house', 'owner']])
  614. self.assertEqual(lst1, lst2)
  615. with self.assertNumQueries(2):
  616. houses = House.objects.select_related('owner')
  617. rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all(), to_attr='house_attr'))
  618. lst2 = self.traverse_qs(rooms, [['house_attr', 'owner']])
  619. self.assertEqual(lst1, lst2)
  620. room = Room.objects.all().prefetch_related(
  621. Prefetch('house', queryset=houses.filter(address='DoesNotExist'))
  622. ).first()
  623. with self.assertRaises(ObjectDoesNotExist):
  624. getattr(room, 'house')
  625. room = Room.objects.all().prefetch_related(
  626. Prefetch('house', queryset=houses.filter(address='DoesNotExist'), to_attr='house_attr')
  627. ).first()
  628. self.assertIsNone(room.house_attr)
  629. rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=House.objects.only('name')))
  630. with self.assertNumQueries(2):
  631. getattr(rooms.first().house, 'name')
  632. with self.assertNumQueries(3):
  633. getattr(rooms.first().house, 'address')
  634. # Test ReverseOneToOneDescriptor.
  635. houses = House.objects.select_related('owner')
  636. with self.assertNumQueries(6):
  637. rooms = Room.objects.all().prefetch_related('main_room_of')
  638. lst1 = self.traverse_qs(rooms, [['main_room_of', 'owner']])
  639. with self.assertNumQueries(2):
  640. rooms = Room.objects.all().prefetch_related(Prefetch('main_room_of', queryset=houses.all()))
  641. lst2 = self.traverse_qs(rooms, [['main_room_of', 'owner']])
  642. self.assertEqual(lst1, lst2)
  643. with self.assertNumQueries(2):
  644. rooms = list(
  645. Room.objects.all().prefetch_related(
  646. Prefetch('main_room_of', queryset=houses.all(), to_attr='main_room_of_attr')
  647. )
  648. )
  649. lst2 = self.traverse_qs(rooms, [['main_room_of_attr', 'owner']])
  650. self.assertEqual(lst1, lst2)
  651. room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(
  652. Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'))
  653. ).first()
  654. with self.assertRaises(ObjectDoesNotExist):
  655. getattr(room, 'main_room_of')
  656. room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(
  657. Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'), to_attr='main_room_of_attr')
  658. ).first()
  659. self.assertIsNone(room.main_room_of_attr)
  660. # The custom queryset filters should be applied to the queryset
  661. # instance returned by the manager.
  662. person = Person.objects.prefetch_related(
  663. Prefetch('houses', queryset=House.objects.filter(name='House 1')),
  664. ).get(pk=self.person1.pk)
  665. self.assertEqual(
  666. list(person.houses.all()),
  667. list(person.houses.all().all()),
  668. )
  669. def test_nested_prefetch_related_are_not_overwritten(self):
  670. # Regression test for #24873
  671. houses_2 = House.objects.prefetch_related(Prefetch('rooms'))
  672. persons = Person.objects.prefetch_related(Prefetch('houses', queryset=houses_2))
  673. houses = House.objects.prefetch_related(Prefetch('occupants', queryset=persons))
  674. list(houses) # queryset must be evaluated once to reproduce the bug.
  675. self.assertEqual(
  676. houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0],
  677. self.room2_1
  678. )
  679. def test_nested_prefetch_related_with_duplicate_prefetcher(self):
  680. """
  681. Nested prefetches whose name clashes with descriptor names
  682. (Person.houses here) are allowed.
  683. """
  684. occupants = Person.objects.prefetch_related(
  685. Prefetch('houses', to_attr='some_attr_name'),
  686. Prefetch('houses', queryset=House.objects.prefetch_related('main_room')),
  687. )
  688. houses = House.objects.prefetch_related(Prefetch('occupants', queryset=occupants))
  689. with self.assertNumQueries(5):
  690. self.traverse_qs(list(houses), [['occupants', 'houses', 'main_room']])
  691. def test_values_queryset(self):
  692. with self.assertRaisesMessage(ValueError, 'Prefetch querysets cannot use values().'):
  693. Prefetch('houses', House.objects.values('pk'))
  694. # That error doesn't affect managers with custom ModelIterable subclasses
  695. self.assertIs(Teacher.objects_custom.all()._iterable_class, ModelIterableSubclass)
  696. Prefetch('teachers', Teacher.objects_custom.all())
  697. def test_to_attr_doesnt_cache_through_attr_as_list(self):
  698. house = House.objects.prefetch_related(
  699. Prefetch('rooms', queryset=Room.objects.all(), to_attr='to_rooms'),
  700. ).get(pk=self.house3.pk)
  701. self.assertIsInstance(house.rooms.all(), QuerySet)
  702. def test_to_attr_cached_property(self):
  703. persons = Person.objects.prefetch_related(
  704. Prefetch('houses', House.objects.all(), to_attr='cached_all_houses'),
  705. )
  706. for person in persons:
  707. # To bypass caching at the related descriptor level, don't use
  708. # person.houses.all() here.
  709. all_houses = list(House.objects.filter(occupants=person))
  710. with self.assertNumQueries(0):
  711. self.assertEqual(person.cached_all_houses, all_houses)
  712. class DefaultManagerTests(TestCase):
  713. def setUp(self):
  714. self.qual1 = Qualification.objects.create(name="BA")
  715. self.qual2 = Qualification.objects.create(name="BSci")
  716. self.qual3 = Qualification.objects.create(name="MA")
  717. self.qual4 = Qualification.objects.create(name="PhD")
  718. self.teacher1 = Teacher.objects.create(name="Mr Cleese")
  719. self.teacher2 = Teacher.objects.create(name="Mr Idle")
  720. self.teacher3 = Teacher.objects.create(name="Mr Chapman")
  721. self.teacher1.qualifications.add(self.qual1, self.qual2, self.qual3, self.qual4)
  722. self.teacher2.qualifications.add(self.qual1)
  723. self.teacher3.qualifications.add(self.qual2)
  724. self.dept1 = Department.objects.create(name="English")
  725. self.dept2 = Department.objects.create(name="Physics")
  726. self.dept1.teachers.add(self.teacher1, self.teacher2)
  727. self.dept2.teachers.add(self.teacher1, self.teacher3)
  728. def test_m2m_then_m2m(self):
  729. with self.assertNumQueries(3):
  730. # When we prefetch the teachers, and force the query, we don't want
  731. # the default manager on teachers to immediately get all the related
  732. # qualifications, since this will do one query per teacher.
  733. qs = Department.objects.prefetch_related('teachers')
  734. depts = "".join("%s department: %s\n" %
  735. (dept.name, ", ".join(str(t) for t in dept.teachers.all()))
  736. for dept in qs)
  737. self.assertEqual(depts,
  738. "English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
  739. "Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman (BSci)\n")
  740. class GenericRelationTests(TestCase):
  741. @classmethod
  742. def setUpTestData(cls):
  743. book1 = Book.objects.create(title="Winnie the Pooh")
  744. book2 = Book.objects.create(title="Do you like green eggs and spam?")
  745. book3 = Book.objects.create(title="Three Men In A Boat")
  746. reader1 = Reader.objects.create(name="me")
  747. reader2 = Reader.objects.create(name="you")
  748. reader3 = Reader.objects.create(name="someone")
  749. book1.read_by.add(reader1, reader2)
  750. book2.read_by.add(reader2)
  751. book3.read_by.add(reader3)
  752. cls.book1, cls.book2, cls.book3 = book1, book2, book3
  753. cls.reader1, cls.reader2, cls.reader3 = reader1, reader2, reader3
  754. def test_prefetch_GFK(self):
  755. TaggedItem.objects.create(tag="awesome", content_object=self.book1)
  756. TaggedItem.objects.create(tag="great", content_object=self.reader1)
  757. TaggedItem.objects.create(tag="outstanding", content_object=self.book2)
  758. TaggedItem.objects.create(tag="amazing", content_object=self.reader3)
  759. # 1 for TaggedItem table, 1 for Book table, 1 for Reader table
  760. with self.assertNumQueries(3):
  761. qs = TaggedItem.objects.prefetch_related('content_object')
  762. list(qs)
  763. def test_prefetch_GFK_nonint_pk(self):
  764. Comment.objects.create(comment="awesome", content_object=self.book1)
  765. # 1 for Comment table, 1 for Book table
  766. with self.assertNumQueries(2):
  767. qs = Comment.objects.prefetch_related('content_object')
  768. [c.content_object for c in qs]
  769. def test_traverse_GFK(self):
  770. """
  771. A 'content_object' can be traversed with prefetch_related() and
  772. get to related objects on the other side (assuming it is suitably
  773. filtered)
  774. """
  775. TaggedItem.objects.create(tag="awesome", content_object=self.book1)
  776. TaggedItem.objects.create(tag="awesome", content_object=self.book2)
  777. TaggedItem.objects.create(tag="awesome", content_object=self.book3)
  778. TaggedItem.objects.create(tag="awesome", content_object=self.reader1)
  779. TaggedItem.objects.create(tag="awesome", content_object=self.reader2)
  780. ct = ContentType.objects.get_for_model(Book)
  781. # We get 3 queries - 1 for main query, 1 for content_objects since they
  782. # all use the same table, and 1 for the 'read_by' relation.
  783. with self.assertNumQueries(3):
  784. # If we limit to books, we know that they will have 'read_by'
  785. # attributes, so the following makes sense:
  786. qs = TaggedItem.objects.filter(content_type=ct, tag='awesome').prefetch_related('content_object__read_by')
  787. readers_of_awesome_books = {r.name for tag in qs
  788. for r in tag.content_object.read_by.all()}
  789. self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"})
  790. def test_nullable_GFK(self):
  791. TaggedItem.objects.create(tag="awesome", content_object=self.book1,
  792. created_by=self.reader1)
  793. TaggedItem.objects.create(tag="great", content_object=self.book2)
  794. TaggedItem.objects.create(tag="rubbish", content_object=self.book3)
  795. with self.assertNumQueries(2):
  796. result = [t.created_by for t in TaggedItem.objects.prefetch_related('created_by')]
  797. self.assertEqual(result,
  798. [t.created_by for t in TaggedItem.objects.all()])
  799. def test_generic_relation(self):
  800. bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
  801. TaggedItem.objects.create(content_object=bookmark, tag='django')
  802. TaggedItem.objects.create(content_object=bookmark, tag='python')
  803. with self.assertNumQueries(2):
  804. tags = [t.tag for b in Bookmark.objects.prefetch_related('tags')
  805. for t in b.tags.all()]
  806. self.assertEqual(sorted(tags), ["django", "python"])
  807. def test_charfield_GFK(self):
  808. b = Bookmark.objects.create(url='http://www.djangoproject.com/')
  809. TaggedItem.objects.create(content_object=b, tag='django')
  810. TaggedItem.objects.create(content_object=b, favorite=b, tag='python')
  811. with self.assertNumQueries(3):
  812. bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
  813. self.assertEqual(sorted(i.tag for i in bookmark.tags.all()), ["django", "python"])
  814. self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
  815. def test_custom_queryset(self):
  816. bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
  817. django_tag = TaggedItem.objects.create(content_object=bookmark, tag='django')
  818. TaggedItem.objects.create(content_object=bookmark, tag='python')
  819. with self.assertNumQueries(2):
  820. bookmark = Bookmark.objects.prefetch_related(
  821. Prefetch('tags', TaggedItem.objects.filter(tag='django')),
  822. ).get()
  823. with self.assertNumQueries(0):
  824. self.assertEqual(list(bookmark.tags.all()), [django_tag])
  825. # The custom queryset filters should be applied to the queryset
  826. # instance returned by the manager.
  827. self.assertEqual(list(bookmark.tags.all()), list(bookmark.tags.all().all()))
  828. class MultiTableInheritanceTest(TestCase):
  829. @classmethod
  830. def setUpTestData(cls):
  831. cls.book1 = BookWithYear.objects.create(title='Poems', published_year=2010)
  832. cls.book2 = BookWithYear.objects.create(title='More poems', published_year=2011)
  833. cls.author1 = AuthorWithAge.objects.create(name='Jane', first_book=cls.book1, age=50)
  834. cls.author2 = AuthorWithAge.objects.create(name='Tom', first_book=cls.book1, age=49)
  835. cls.author3 = AuthorWithAge.objects.create(name='Robert', first_book=cls.book2, age=48)
  836. cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1')
  837. cls.book2.aged_authors.add(cls.author2, cls.author3)
  838. cls.br1 = BookReview.objects.create(book=cls.book1, notes='review book1')
  839. cls.br2 = BookReview.objects.create(book=cls.book2, notes='review book2')
  840. def test_foreignkey(self):
  841. with self.assertNumQueries(2):
  842. qs = AuthorWithAge.objects.prefetch_related('addresses')
  843. addresses = [[str(address) for address in obj.addresses.all()] for obj in qs]
  844. self.assertEqual(addresses, [[str(self.author_address)], [], []])
  845. def test_foreignkey_to_inherited(self):
  846. with self.assertNumQueries(2):
  847. qs = BookReview.objects.prefetch_related('book')
  848. titles = [obj.book.title for obj in qs]
  849. self.assertEqual(titles, ["Poems", "More poems"])
  850. def test_m2m_to_inheriting_model(self):
  851. qs = AuthorWithAge.objects.prefetch_related('books_with_year')
  852. with self.assertNumQueries(2):
  853. lst = [[str(book) for book in author.books_with_year.all()] for author in qs]
  854. qs = AuthorWithAge.objects.all()
  855. lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs]
  856. self.assertEqual(lst, lst2)
  857. qs = BookWithYear.objects.prefetch_related('aged_authors')
  858. with self.assertNumQueries(2):
  859. lst = [[str(author) for author in book.aged_authors.all()] for book in qs]
  860. qs = BookWithYear.objects.all()
  861. lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs]
  862. self.assertEqual(lst, lst2)
  863. def test_parent_link_prefetch(self):
  864. with self.assertNumQueries(2):
  865. [a.author for a in AuthorWithAge.objects.prefetch_related('author')]
  866. @override_settings(DEBUG=True)
  867. def test_child_link_prefetch(self):
  868. with self.assertNumQueries(2):
  869. authors = [a.authorwithage for a in Author.objects.prefetch_related('authorwithage')]
  870. # Regression for #18090: the prefetching query must include an IN clause.
  871. # Note that on Oracle the table name is upper case in the generated SQL,
  872. # thus the .lower() call.
  873. self.assertIn('authorwithage', connection.queries[-1]['sql'].lower())
  874. self.assertIn(' IN ', connection.queries[-1]['sql'])
  875. self.assertEqual(authors, [a.authorwithage for a in Author.objects.all()])
  876. class ForeignKeyToFieldTest(TestCase):
  877. @classmethod
  878. def setUpTestData(cls):
  879. cls.book = Book.objects.create(title='Poems')
  880. cls.author1 = Author.objects.create(name='Jane', first_book=cls.book)
  881. cls.author2 = Author.objects.create(name='Tom', first_book=cls.book)
  882. cls.author3 = Author.objects.create(name='Robert', first_book=cls.book)
  883. cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1')
  884. FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
  885. FavoriteAuthors.objects.create(author=cls.author2, likes_author=cls.author3)
  886. FavoriteAuthors.objects.create(author=cls.author3, likes_author=cls.author1)
  887. def test_foreignkey(self):
  888. with self.assertNumQueries(2):
  889. qs = Author.objects.prefetch_related('addresses')
  890. addresses = [[str(address) for address in obj.addresses.all()]
  891. for obj in qs]
  892. self.assertEqual(addresses, [[str(self.author_address)], [], []])
  893. def test_m2m(self):
  894. with self.assertNumQueries(3):
  895. qs = Author.objects.all().prefetch_related('favorite_authors', 'favors_me')
  896. favorites = [(
  897. [str(i_like) for i_like in author.favorite_authors.all()],
  898. [str(likes_me) for likes_me in author.favors_me.all()]
  899. ) for author in qs]
  900. self.assertEqual(
  901. favorites,
  902. [
  903. ([str(self.author2)], [str(self.author3)]),
  904. ([str(self.author3)], [str(self.author1)]),
  905. ([str(self.author1)], [str(self.author2)])
  906. ]
  907. )
  908. class LookupOrderingTest(TestCase):
  909. """
  910. Test cases that demonstrate that ordering of lookups is important, and
  911. ensure it is preserved.
  912. """
  913. def setUp(self):
  914. self.person1 = Person.objects.create(name="Joe")
  915. self.person2 = Person.objects.create(name="Mary")
  916. # Set main_room for each house before creating the next one for
  917. # databases where supports_nullable_unique_constraints is False.
  918. self.house1 = House.objects.create(address="123 Main St")
  919. self.room1_1 = Room.objects.create(name="Dining room", house=self.house1)
  920. self.room1_2 = Room.objects.create(name="Lounge", house=self.house1)
  921. self.room1_3 = Room.objects.create(name="Kitchen", house=self.house1)
  922. self.house1.main_room = self.room1_1
  923. self.house1.save()
  924. self.person1.houses.add(self.house1)
  925. self.house2 = House.objects.create(address="45 Side St")
  926. self.room2_1 = Room.objects.create(name="Dining room", house=self.house2)
  927. self.room2_2 = Room.objects.create(name="Lounge", house=self.house2)
  928. self.house2.main_room = self.room2_1
  929. self.house2.save()
  930. self.person1.houses.add(self.house2)
  931. self.house3 = House.objects.create(address="6 Downing St")
  932. self.room3_1 = Room.objects.create(name="Dining room", house=self.house3)
  933. self.room3_2 = Room.objects.create(name="Lounge", house=self.house3)
  934. self.room3_3 = Room.objects.create(name="Kitchen", house=self.house3)
  935. self.house3.main_room = self.room3_1
  936. self.house3.save()
  937. self.person2.houses.add(self.house3)
  938. self.house4 = House.objects.create(address="7 Regents St")
  939. self.room4_1 = Room.objects.create(name="Dining room", house=self.house4)
  940. self.room4_2 = Room.objects.create(name="Lounge", house=self.house4)
  941. self.house4.main_room = self.room4_1
  942. self.house4.save()
  943. self.person2.houses.add(self.house4)
  944. def test_order(self):
  945. with self.assertNumQueries(4):
  946. # The following two queries must be done in the same order as written,
  947. # otherwise 'primary_house' will cause non-prefetched lookups
  948. qs = Person.objects.prefetch_related('houses__rooms',
  949. 'primary_house__occupants')
  950. [list(p.primary_house.occupants.all()) for p in qs]
  951. class NullableTest(TestCase):
  952. @classmethod
  953. def setUpTestData(cls):
  954. boss = Employee.objects.create(name="Peter")
  955. Employee.objects.create(name="Joe", boss=boss)
  956. Employee.objects.create(name="Angela", boss=boss)
  957. def test_traverse_nullable(self):
  958. # Because we use select_related() for 'boss', it doesn't need to be
  959. # prefetched, but we can still traverse it although it contains some nulls
  960. with self.assertNumQueries(2):
  961. qs = Employee.objects.select_related('boss').prefetch_related('boss__serfs')
  962. co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else []
  963. for e in qs]
  964. qs2 = Employee.objects.select_related('boss')
  965. co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2]
  966. self.assertEqual(co_serfs, co_serfs2)
  967. def test_prefetch_nullable(self):
  968. # One for main employee, one for boss, one for serfs
  969. with self.assertNumQueries(3):
  970. qs = Employee.objects.prefetch_related('boss__serfs')
  971. co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else []
  972. for e in qs]
  973. qs2 = Employee.objects.all()
  974. co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2]
  975. self.assertEqual(co_serfs, co_serfs2)
  976. def test_in_bulk(self):
  977. """
  978. In-bulk does correctly prefetch objects by not using .iterator()
  979. directly.
  980. """
  981. boss1 = Employee.objects.create(name="Peter")
  982. boss2 = Employee.objects.create(name="Jack")
  983. with self.assertNumQueries(2):
  984. # Prefetch is done and it does not cause any errors.
  985. bulk = Employee.objects.prefetch_related('serfs').in_bulk([boss1.pk, boss2.pk])
  986. for b in bulk.values():
  987. list(b.serfs.all())
  988. class MultiDbTests(TestCase):
  989. databases = {'default', 'other'}
  990. def test_using_is_honored_m2m(self):
  991. B = Book.objects.using('other')
  992. A = Author.objects.using('other')
  993. book1 = B.create(title="Poems")
  994. book2 = B.create(title="Jane Eyre")
  995. book3 = B.create(title="Wuthering Heights")
  996. book4 = B.create(title="Sense and Sensibility")
  997. author1 = A.create(name="Charlotte", first_book=book1)
  998. author2 = A.create(name="Anne", first_book=book1)
  999. author3 = A.create(name="Emily", first_book=book1)
  1000. author4 = A.create(name="Jane", first_book=book4)
  1001. book1.authors.add(author1, author2, author3)
  1002. book2.authors.add(author1)
  1003. book3.authors.add(author3)
  1004. book4.authors.add(author4)
  1005. # Forward
  1006. qs1 = B.prefetch_related('authors')
  1007. with self.assertNumQueries(2, using='other'):
  1008. books = "".join("%s (%s)\n" %
  1009. (book.title, ", ".join(a.name for a in book.authors.all()))
  1010. for book in qs1)
  1011. self.assertEqual(books,
  1012. "Poems (Charlotte, Anne, Emily)\n"
  1013. "Jane Eyre (Charlotte)\n"
  1014. "Wuthering Heights (Emily)\n"
  1015. "Sense and Sensibility (Jane)\n")
  1016. # Reverse
  1017. qs2 = A.prefetch_related('books')
  1018. with self.assertNumQueries(2, using='other'):
  1019. authors = "".join("%s: %s\n" %
  1020. (author.name, ", ".join(b.title for b in author.books.all()))
  1021. for author in qs2)
  1022. self.assertEqual(authors,
  1023. "Charlotte: Poems, Jane Eyre\n"
  1024. "Anne: Poems\n"
  1025. "Emily: Poems, Wuthering Heights\n"
  1026. "Jane: Sense and Sensibility\n")
  1027. def test_using_is_honored_fkey(self):
  1028. B = Book.objects.using('other')
  1029. A = Author.objects.using('other')
  1030. book1 = B.create(title="Poems")
  1031. book2 = B.create(title="Sense and Sensibility")
  1032. A.create(name="Charlotte Bronte", first_book=book1)
  1033. A.create(name="Jane Austen", first_book=book2)
  1034. # Forward
  1035. with self.assertNumQueries(2, using='other'):
  1036. books = ", ".join(a.first_book.title for a in A.prefetch_related('first_book'))
  1037. self.assertEqual("Poems, Sense and Sensibility", books)
  1038. # Reverse
  1039. with self.assertNumQueries(2, using='other'):
  1040. books = "".join("%s (%s)\n" %
  1041. (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1042. for b in B.prefetch_related('first_time_authors'))
  1043. self.assertEqual(books,
  1044. "Poems (Charlotte Bronte)\n"
  1045. "Sense and Sensibility (Jane Austen)\n")
  1046. def test_using_is_honored_inheritance(self):
  1047. B = BookWithYear.objects.using('other')
  1048. A = AuthorWithAge.objects.using('other')
  1049. book1 = B.create(title="Poems", published_year=2010)
  1050. B.create(title="More poems", published_year=2011)
  1051. A.create(name='Jane', first_book=book1, age=50)
  1052. A.create(name='Tom', first_book=book1, age=49)
  1053. # parent link
  1054. with self.assertNumQueries(2, using='other'):
  1055. authors = ", ".join(a.author.name for a in A.prefetch_related('author'))
  1056. self.assertEqual(authors, "Jane, Tom")
  1057. # child link
  1058. with self.assertNumQueries(2, using='other'):
  1059. ages = ", ".join(str(a.authorwithage.age) for a in A.prefetch_related('authorwithage'))
  1060. self.assertEqual(ages, "50, 49")
  1061. def test_using_is_honored_custom_qs(self):
  1062. B = Book.objects.using('other')
  1063. A = Author.objects.using('other')
  1064. book1 = B.create(title="Poems")
  1065. book2 = B.create(title="Sense and Sensibility")
  1066. A.create(name="Charlotte Bronte", first_book=book1)
  1067. A.create(name="Jane Austen", first_book=book2)
  1068. # Implicit hinting
  1069. with self.assertNumQueries(2, using='other'):
  1070. prefetch = Prefetch('first_time_authors', queryset=Author.objects.all())
  1071. books = "".join("%s (%s)\n" %
  1072. (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1073. for b in B.prefetch_related(prefetch))
  1074. self.assertEqual(books,
  1075. "Poems (Charlotte Bronte)\n"
  1076. "Sense and Sensibility (Jane Austen)\n")
  1077. # Explicit using on the same db.
  1078. with self.assertNumQueries(2, using='other'):
  1079. prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('other'))
  1080. books = "".join("%s (%s)\n" %
  1081. (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1082. for b in B.prefetch_related(prefetch))
  1083. self.assertEqual(books,
  1084. "Poems (Charlotte Bronte)\n"
  1085. "Sense and Sensibility (Jane Austen)\n")
  1086. # Explicit using on a different db.
  1087. with self.assertNumQueries(1, using='default'), self.assertNumQueries(1, using='other'):
  1088. prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('default'))
  1089. books = "".join("%s (%s)\n" %
  1090. (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
  1091. for b in B.prefetch_related(prefetch))
  1092. self.assertEqual(books,
  1093. "Poems ()\n"
  1094. "Sense and Sensibility ()\n")
  1095. class Ticket19607Tests(TestCase):
  1096. def setUp(self):
  1097. for id, name1, name2 in [
  1098. (1, 'einfach', 'simple'),
  1099. (2, 'schwierig', 'difficult'),
  1100. ]:
  1101. LessonEntry.objects.create(id=id, name1=name1, name2=name2)
  1102. for id, lesson_entry_id, name in [
  1103. (1, 1, 'einfach'),
  1104. (2, 1, 'simple'),
  1105. (3, 2, 'schwierig'),
  1106. (4, 2, 'difficult'),
  1107. ]:
  1108. WordEntry.objects.create(id=id, lesson_entry_id=lesson_entry_id, name=name)
  1109. def test_bug(self):
  1110. list(WordEntry.objects.prefetch_related('lesson_entry', 'lesson_entry__wordentry_set'))
  1111. class Ticket21410Tests(TestCase):
  1112. def setUp(self):
  1113. self.book1 = Book.objects.create(title="Poems")
  1114. self.book2 = Book.objects.create(title="Jane Eyre")
  1115. self.book3 = Book.objects.create(title="Wuthering Heights")
  1116. self.book4 = Book.objects.create(title="Sense and Sensibility")
  1117. self.author1 = Author2.objects.create(name="Charlotte", first_book=self.book1)
  1118. self.author2 = Author2.objects.create(name="Anne", first_book=self.book1)
  1119. self.author3 = Author2.objects.create(name="Emily", first_book=self.book1)
  1120. self.author4 = Author2.objects.create(name="Jane", first_book=self.book4)
  1121. self.author1.favorite_books.add(self.book1, self.book2, self.book3)
  1122. self.author2.favorite_books.add(self.book1)
  1123. self.author3.favorite_books.add(self.book2)
  1124. self.author4.favorite_books.add(self.book3)
  1125. def test_bug(self):
  1126. list(Author2.objects.prefetch_related('first_book', 'favorite_books'))
  1127. class Ticket21760Tests(TestCase):
  1128. def setUp(self):
  1129. self.rooms = []
  1130. for _ in range(3):
  1131. house = House.objects.create()
  1132. for _ in range(3):
  1133. self.rooms.append(Room.objects.create(house=house))
  1134. # Set main_room for each house before creating the next one for
  1135. # databases where supports_nullable_unique_constraints is False.
  1136. house.main_room = self.rooms[-3]
  1137. house.save()
  1138. def test_bug(self):
  1139. prefetcher = get_prefetcher(self.rooms[0], 'house', 'house')[0]
  1140. queryset = prefetcher.get_prefetch_queryset(list(Room.objects.all()))[0]
  1141. self.assertNotIn(' JOIN ', str(queryset.query))
  1142. class DirectPrefechedObjectCacheReuseTests(TestCase):
  1143. """
  1144. prefetch_related() reuses objects fetched in _prefetched_objects_cache.
  1145. When objects are prefetched and not stored as an instance attribute (often
  1146. intermediary relationships), they are saved to the
  1147. _prefetched_objects_cache attribute. prefetch_related() takes
  1148. _prefetched_objects_cache into account when determining whether an object
  1149. has been fetched[1] and retrieves results from it when it is populated [2].
  1150. [1]: #25546 (duplicate queries on nested Prefetch)
  1151. [2]: #27554 (queryset evaluation fails with a mix of nested and flattened
  1152. prefetches)
  1153. """
  1154. @classmethod
  1155. def setUpTestData(cls):
  1156. cls.book1, cls.book2 = [
  1157. Book.objects.create(title='book1'),
  1158. Book.objects.create(title='book2'),
  1159. ]
  1160. cls.author11, cls.author12, cls.author21 = [
  1161. Author.objects.create(first_book=cls.book1, name='Author11'),
  1162. Author.objects.create(first_book=cls.book1, name='Author12'),
  1163. Author.objects.create(first_book=cls.book2, name='Author21'),
  1164. ]
  1165. cls.author1_address1, cls.author1_address2, cls.author2_address1 = [
  1166. AuthorAddress.objects.create(author=cls.author11, address='Happy place'),
  1167. AuthorAddress.objects.create(author=cls.author12, address='Haunted house'),
  1168. AuthorAddress.objects.create(author=cls.author21, address='Happy place'),
  1169. ]
  1170. cls.bookwithyear1 = BookWithYear.objects.create(title='Poems', published_year=2010)
  1171. cls.bookreview1 = BookReview.objects.create(book=cls.bookwithyear1)
  1172. def test_detect_is_fetched(self):
  1173. """
  1174. Nested prefetch_related() shouldn't trigger duplicate queries for the same
  1175. lookup.
  1176. """
  1177. with self.assertNumQueries(3):
  1178. books = Book.objects.filter(
  1179. title__in=['book1', 'book2'],
  1180. ).prefetch_related(
  1181. Prefetch(
  1182. 'first_time_authors',
  1183. Author.objects.prefetch_related(
  1184. Prefetch(
  1185. 'addresses',
  1186. AuthorAddress.objects.filter(address='Happy place'),
  1187. )
  1188. ),
  1189. ),
  1190. )
  1191. book1, book2 = list(books)
  1192. with self.assertNumQueries(0):
  1193. self.assertSequenceEqual(book1.first_time_authors.all(), [self.author11, self.author12])
  1194. self.assertSequenceEqual(book2.first_time_authors.all(), [self.author21])
  1195. self.assertSequenceEqual(book1.first_time_authors.all()[0].addresses.all(), [self.author1_address1])
  1196. self.assertSequenceEqual(book1.first_time_authors.all()[1].addresses.all(), [])
  1197. self.assertSequenceEqual(book2.first_time_authors.all()[0].addresses.all(), [self.author2_address1])
  1198. self.assertEqual(
  1199. list(book1.first_time_authors.all()), list(book1.first_time_authors.all().all())
  1200. )
  1201. self.assertEqual(
  1202. list(book2.first_time_authors.all()), list(book2.first_time_authors.all().all())
  1203. )
  1204. self.assertEqual(
  1205. list(book1.first_time_authors.all()[0].addresses.all()),
  1206. list(book1.first_time_authors.all()[0].addresses.all().all())
  1207. )
  1208. self.assertEqual(
  1209. list(book1.first_time_authors.all()[1].addresses.all()),
  1210. list(book1.first_time_authors.all()[1].addresses.all().all())
  1211. )
  1212. self.assertEqual(
  1213. list(book2.first_time_authors.all()[0].addresses.all()),
  1214. list(book2.first_time_authors.all()[0].addresses.all().all())
  1215. )
  1216. def test_detect_is_fetched_with_to_attr(self):
  1217. with self.assertNumQueries(3):
  1218. books = Book.objects.filter(
  1219. title__in=['book1', 'book2'],
  1220. ).prefetch_related(
  1221. Prefetch(
  1222. 'first_time_authors',
  1223. Author.objects.prefetch_related(
  1224. Prefetch(
  1225. 'addresses',
  1226. AuthorAddress.objects.filter(address='Happy place'),
  1227. to_attr='happy_place',
  1228. )
  1229. ),
  1230. to_attr='first_authors',
  1231. ),
  1232. )
  1233. book1, book2 = list(books)
  1234. with self.assertNumQueries(0):
  1235. self.assertEqual(book1.first_authors, [self.author11, self.author12])
  1236. self.assertEqual(book2.first_authors, [self.author21])
  1237. self.assertEqual(book1.first_authors[0].happy_place, [self.author1_address1])
  1238. self.assertEqual(book1.first_authors[1].happy_place, [])
  1239. self.assertEqual(book2.first_authors[0].happy_place, [self.author2_address1])
  1240. def test_prefetch_reverse_foreign_key(self):
  1241. with self.assertNumQueries(2):
  1242. bookwithyear1, = BookWithYear.objects.prefetch_related('bookreview_set')
  1243. with self.assertNumQueries(0):
  1244. self.assertCountEqual(bookwithyear1.bookreview_set.all(), [self.bookreview1])
  1245. with self.assertNumQueries(0):
  1246. prefetch_related_objects([bookwithyear1], 'bookreview_set')
  1247. def test_add_clears_prefetched_objects(self):
  1248. bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
  1249. prefetch_related_objects([bookwithyear], 'bookreview_set')
  1250. self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
  1251. new_review = BookReview.objects.create()
  1252. bookwithyear.bookreview_set.add(new_review)
  1253. self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1, new_review])
  1254. def test_remove_clears_prefetched_objects(self):
  1255. bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
  1256. prefetch_related_objects([bookwithyear], 'bookreview_set')
  1257. self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
  1258. bookwithyear.bookreview_set.remove(self.bookreview1)
  1259. self.assertCountEqual(bookwithyear.bookreview_set.all(), [])
  1260. class ReadPrefetchedObjectsCacheTests(TestCase):
  1261. @classmethod
  1262. def setUpTestData(cls):
  1263. cls.book1 = Book.objects.create(title='Les confessions Volume I')
  1264. cls.book2 = Book.objects.create(title='Candide')
  1265. cls.author1 = AuthorWithAge.objects.create(name='Rousseau', first_book=cls.book1, age=70)
  1266. cls.author2 = AuthorWithAge.objects.create(name='Voltaire', first_book=cls.book2, age=65)
  1267. cls.book1.authors.add(cls.author1)
  1268. cls.book2.authors.add(cls.author2)
  1269. FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
  1270. def test_retrieves_results_from_prefetched_objects_cache(self):
  1271. """
  1272. When intermediary results are prefetched without a destination
  1273. attribute, they are saved in the RelatedManager's cache
  1274. (_prefetched_objects_cache). prefetch_related() uses this cache
  1275. (#27554).
  1276. """
  1277. authors = AuthorWithAge.objects.prefetch_related(
  1278. Prefetch(
  1279. 'author',
  1280. queryset=Author.objects.prefetch_related(
  1281. # Results are saved in the RelatedManager's cache
  1282. # (_prefetched_objects_cache) and do not replace the
  1283. # RelatedManager on Author instances (favorite_authors)
  1284. Prefetch('favorite_authors__first_book'),
  1285. ),
  1286. ),
  1287. )
  1288. with self.assertNumQueries(4):
  1289. # AuthorWithAge -> Author -> FavoriteAuthors, Book
  1290. self.assertQuerysetEqual(authors, ['<AuthorWithAge: Rousseau>', '<AuthorWithAge: Voltaire>'])