tests.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. from django.contrib.contenttypes.models import ContentType
  2. from django.core.exceptions import FieldError
  3. from django.db import IntegrityError
  4. from django.db.models import Q
  5. from django.test import SimpleTestCase, TestCase
  6. from .models import (
  7. AllowsNullGFK, Animal, Carrot, Comparison, ConcreteRelatedModel,
  8. ForConcreteModelModel, ForProxyModelModel, Gecko, ManualPK, Mineral,
  9. ProxyRelatedModel, Rock, TaggedItem, ValuableRock, ValuableTaggedItem,
  10. Vegetable,
  11. )
  12. class GenericRelationsTests(TestCase):
  13. @classmethod
  14. def setUpTestData(cls):
  15. cls.lion = Animal.objects.create(common_name='Lion', latin_name='Panthera leo')
  16. cls.platypus = Animal.objects.create(
  17. common_name='Platypus',
  18. latin_name='Ornithorhynchus anatinus',
  19. )
  20. Vegetable.objects.create(name="Eggplant", is_yucky=True)
  21. cls.bacon = Vegetable.objects.create(name='Bacon', is_yucky=False)
  22. cls.quartz = Mineral.objects.create(name='Quartz', hardness=7)
  23. # Tagging stuff.
  24. cls.fatty = cls.bacon.tags.create(tag='fatty')
  25. cls.salty = cls.bacon.tags.create(tag='salty')
  26. cls.yellow = cls.lion.tags.create(tag='yellow')
  27. cls.hairy = cls.lion.tags.create(tag='hairy')
  28. def comp_func(self, obj):
  29. # Original list of tags:
  30. return obj.tag, obj.content_type.model_class(), obj.object_id
  31. def test_generic_update_or_create_when_created(self):
  32. """
  33. Should be able to use update_or_create from the generic related manager
  34. to create a tag. Refs #23611.
  35. """
  36. count = self.bacon.tags.count()
  37. tag, created = self.bacon.tags.update_or_create(tag='stinky')
  38. self.assertTrue(created)
  39. self.assertEqual(count + 1, self.bacon.tags.count())
  40. def test_generic_update_or_create_when_updated(self):
  41. """
  42. Should be able to use update_or_create from the generic related manager
  43. to update a tag. Refs #23611.
  44. """
  45. count = self.bacon.tags.count()
  46. tag = self.bacon.tags.create(tag='stinky')
  47. self.assertEqual(count + 1, self.bacon.tags.count())
  48. tag, created = self.bacon.tags.update_or_create(defaults={'tag': 'juicy'}, id=tag.id)
  49. self.assertFalse(created)
  50. self.assertEqual(count + 1, self.bacon.tags.count())
  51. self.assertEqual(tag.tag, 'juicy')
  52. def test_generic_get_or_create_when_created(self):
  53. """
  54. Should be able to use get_or_create from the generic related manager
  55. to create a tag. Refs #23611.
  56. """
  57. count = self.bacon.tags.count()
  58. tag, created = self.bacon.tags.get_or_create(tag='stinky')
  59. self.assertTrue(created)
  60. self.assertEqual(count + 1, self.bacon.tags.count())
  61. def test_generic_get_or_create_when_exists(self):
  62. """
  63. Should be able to use get_or_create from the generic related manager
  64. to get a tag. Refs #23611.
  65. """
  66. count = self.bacon.tags.count()
  67. tag = self.bacon.tags.create(tag="stinky")
  68. self.assertEqual(count + 1, self.bacon.tags.count())
  69. tag, created = self.bacon.tags.get_or_create(id=tag.id, defaults={'tag': 'juicy'})
  70. self.assertFalse(created)
  71. self.assertEqual(count + 1, self.bacon.tags.count())
  72. # shouldn't had changed the tag
  73. self.assertEqual(tag.tag, 'stinky')
  74. def test_generic_relations_m2m_mimic(self):
  75. """
  76. Objects with declared GenericRelations can be tagged directly -- the
  77. API mimics the many-to-many API.
  78. """
  79. self.assertSequenceEqual(self.lion.tags.all(), [self.hairy, self.yellow])
  80. self.assertSequenceEqual(self.bacon.tags.all(), [self.fatty, self.salty])
  81. def test_access_content_object(self):
  82. """
  83. Test accessing the content object like a foreign key.
  84. """
  85. tagged_item = TaggedItem.objects.get(tag="salty")
  86. self.assertEqual(tagged_item.content_object, self.bacon)
  87. def test_query_content_object(self):
  88. qs = TaggedItem.objects.filter(
  89. animal__isnull=False).order_by('animal__common_name', 'tag')
  90. self.assertSequenceEqual(qs, [self.hairy, self.yellow])
  91. mpk = ManualPK.objects.create(id=1)
  92. mpk.tags.create(tag='mpk')
  93. qs = TaggedItem.objects.filter(
  94. Q(animal__isnull=False) | Q(manualpk__id=1)).order_by('tag')
  95. self.assertQuerysetEqual(
  96. qs, ["hairy", "mpk", "yellow"], lambda x: x.tag)
  97. def test_exclude_generic_relations(self):
  98. """
  99. Test lookups over an object without GenericRelations.
  100. """
  101. # Recall that the Mineral class doesn't have an explicit GenericRelation
  102. # defined. That's OK, because you can create TaggedItems explicitly.
  103. # However, excluding GenericRelations means your lookups have to be a
  104. # bit more explicit.
  105. shiny = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  106. clearish = TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  107. ctype = ContentType.objects.get_for_model(self.quartz)
  108. q = TaggedItem.objects.filter(
  109. content_type__pk=ctype.id, object_id=self.quartz.id
  110. )
  111. self.assertSequenceEqual(q, [clearish, shiny])
  112. def test_access_via_content_type(self):
  113. """
  114. Test lookups through content type.
  115. """
  116. self.lion.delete()
  117. self.platypus.tags.create(tag="fatty")
  118. ctype = ContentType.objects.get_for_model(self.platypus)
  119. self.assertSequenceEqual(
  120. Animal.objects.filter(tags__content_type=ctype),
  121. [self.platypus],
  122. )
  123. def test_set_foreign_key(self):
  124. """
  125. You can set a generic foreign key in the way you'd expect.
  126. """
  127. tag1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  128. tag1.content_object = self.platypus
  129. tag1.save()
  130. self.assertSequenceEqual(self.platypus.tags.all(), [tag1])
  131. def test_queries_across_generic_relations(self):
  132. """
  133. Queries across generic relations respect the content types. Even though
  134. there are two TaggedItems with a tag of "fatty", this query only pulls
  135. out the one with the content type related to Animals.
  136. """
  137. self.assertSequenceEqual(
  138. Animal.objects.order_by('common_name'),
  139. [self.lion, self.platypus],
  140. )
  141. def test_queries_content_type_restriction(self):
  142. """
  143. Create another fatty tagged instance with different PK to ensure there
  144. is a content type restriction in the generated queries below.
  145. """
  146. mpk = ManualPK.objects.create(id=self.lion.pk)
  147. mpk.tags.create(tag="fatty")
  148. self.platypus.tags.create(tag="fatty")
  149. self.assertSequenceEqual(
  150. Animal.objects.filter(tags__tag='fatty'),
  151. [self.platypus],
  152. )
  153. self.assertSequenceEqual(
  154. Animal.objects.exclude(tags__tag='fatty'),
  155. [self.lion],
  156. )
  157. def test_object_deletion_with_generic_relation(self):
  158. """
  159. If you delete an object with an explicit Generic relation, the related
  160. objects are deleted when the source object is deleted.
  161. """
  162. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  163. ('fatty', Vegetable, self.bacon.pk),
  164. ('hairy', Animal, self.lion.pk),
  165. ('salty', Vegetable, self.bacon.pk),
  166. ('yellow', Animal, self.lion.pk)
  167. ],
  168. self.comp_func
  169. )
  170. self.lion.delete()
  171. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  172. ('fatty', Vegetable, self.bacon.pk),
  173. ('salty', Vegetable, self.bacon.pk),
  174. ],
  175. self.comp_func
  176. )
  177. def test_object_deletion_without_generic_relation(self):
  178. """
  179. If Generic Relation is not explicitly defined, any related objects
  180. remain after deletion of the source object.
  181. """
  182. TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  183. quartz_pk = self.quartz.pk
  184. self.quartz.delete()
  185. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  186. ('clearish', Mineral, quartz_pk),
  187. ('fatty', Vegetable, self.bacon.pk),
  188. ('hairy', Animal, self.lion.pk),
  189. ('salty', Vegetable, self.bacon.pk),
  190. ('yellow', Animal, self.lion.pk),
  191. ],
  192. self.comp_func
  193. )
  194. def test_tag_deletion_related_objects_unaffected(self):
  195. """
  196. If you delete a tag, the objects using the tag are unaffected (other
  197. than losing a tag).
  198. """
  199. ctype = ContentType.objects.get_for_model(self.lion)
  200. tag = TaggedItem.objects.get(
  201. content_type__pk=ctype.id, object_id=self.lion.id, tag="hairy")
  202. tag.delete()
  203. self.assertSequenceEqual(self.lion.tags.all(), [self.yellow])
  204. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  205. ('fatty', Vegetable, self.bacon.pk),
  206. ('salty', Vegetable, self.bacon.pk),
  207. ('yellow', Animal, self.lion.pk)
  208. ],
  209. self.comp_func
  210. )
  211. def test_add_bulk(self):
  212. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  213. t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  214. t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  215. # One update() query.
  216. with self.assertNumQueries(1):
  217. bacon.tags.add(t1, t2)
  218. self.assertEqual(t1.content_object, bacon)
  219. self.assertEqual(t2.content_object, bacon)
  220. def test_add_bulk_false(self):
  221. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  222. t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  223. t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  224. # One save() for each object.
  225. with self.assertNumQueries(2):
  226. bacon.tags.add(t1, t2, bulk=False)
  227. self.assertEqual(t1.content_object, bacon)
  228. self.assertEqual(t2.content_object, bacon)
  229. def test_add_rejects_unsaved_objects(self):
  230. t1 = TaggedItem(content_object=self.quartz, tag="shiny")
  231. msg = "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the object first."
  232. with self.assertRaisesMessage(ValueError, msg):
  233. self.bacon.tags.add(t1)
  234. def test_add_rejects_wrong_instances(self):
  235. msg = "'TaggedItem' instance expected, got <Animal: Lion>"
  236. with self.assertRaisesMessage(TypeError, msg):
  237. self.bacon.tags.add(self.lion)
  238. def test_set(self):
  239. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  240. fatty = bacon.tags.create(tag="fatty")
  241. salty = bacon.tags.create(tag="salty")
  242. bacon.tags.set([fatty, salty])
  243. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  244. bacon.tags.set([fatty])
  245. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  246. bacon.tags.set([])
  247. self.assertSequenceEqual(bacon.tags.all(), [])
  248. bacon.tags.set([fatty, salty], bulk=False, clear=True)
  249. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  250. bacon.tags.set([fatty], bulk=False, clear=True)
  251. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  252. bacon.tags.set([], clear=True)
  253. self.assertSequenceEqual(bacon.tags.all(), [])
  254. def test_assign(self):
  255. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  256. fatty = bacon.tags.create(tag="fatty")
  257. salty = bacon.tags.create(tag="salty")
  258. bacon.tags.set([fatty, salty])
  259. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  260. bacon.tags.set([fatty])
  261. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  262. bacon.tags.set([])
  263. self.assertSequenceEqual(bacon.tags.all(), [])
  264. def test_assign_with_queryset(self):
  265. # Querysets used in reverse GFK assignments are pre-evaluated so their
  266. # value isn't affected by the clearing operation
  267. # in ManyRelatedManager.set() (#19816).
  268. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  269. bacon.tags.create(tag="fatty")
  270. bacon.tags.create(tag="salty")
  271. self.assertEqual(2, bacon.tags.count())
  272. qs = bacon.tags.filter(tag="fatty")
  273. bacon.tags.set(qs)
  274. self.assertEqual(1, bacon.tags.count())
  275. self.assertEqual(1, qs.count())
  276. def test_generic_relation_related_name_default(self):
  277. # GenericRelation isn't usable from the reverse side by default.
  278. msg = (
  279. "Cannot resolve keyword 'vegetable' into field. Choices are: "
  280. "animal, content_object, content_type, content_type_id, id, "
  281. "manualpk, object_id, tag, valuabletaggeditem"
  282. )
  283. with self.assertRaisesMessage(FieldError, msg):
  284. TaggedItem.objects.filter(vegetable__isnull=True)
  285. def test_multiple_gfk(self):
  286. # Simple tests for multiple GenericForeignKeys
  287. # only uses one model, since the above tests should be sufficient.
  288. tiger = Animal.objects.create(common_name="tiger")
  289. cheetah = Animal.objects.create(common_name="cheetah")
  290. bear = Animal.objects.create(common_name="bear")
  291. # Create directly
  292. c1 = Comparison.objects.create(
  293. first_obj=cheetah, other_obj=tiger, comparative="faster"
  294. )
  295. c2 = Comparison.objects.create(
  296. first_obj=tiger, other_obj=cheetah, comparative="cooler"
  297. )
  298. # Create using GenericRelation
  299. c3 = tiger.comparisons.create(other_obj=bear, comparative="cooler")
  300. c4 = tiger.comparisons.create(other_obj=cheetah, comparative="stronger")
  301. self.assertSequenceEqual(cheetah.comparisons.all(), [c1])
  302. # Filtering works
  303. self.assertCountEqual(
  304. tiger.comparisons.filter(comparative='cooler'),
  305. [c2, c3],
  306. )
  307. # Filtering and deleting works
  308. subjective = ["cooler"]
  309. tiger.comparisons.filter(comparative__in=subjective).delete()
  310. self.assertCountEqual(Comparison.objects.all(), [c1, c4])
  311. # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be
  312. # deleted since Animal has an explicit GenericRelation to Comparison
  313. # through first_obj. Comparisons with cheetah as 'other_obj' will not
  314. # be deleted.
  315. cheetah.delete()
  316. self.assertSequenceEqual(Comparison.objects.all(), [c4])
  317. def test_gfk_subclasses(self):
  318. # GenericForeignKey should work with subclasses (see #8309)
  319. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  320. valuedtag = ValuableTaggedItem.objects.create(
  321. content_object=quartz, tag="shiny", value=10
  322. )
  323. self.assertEqual(valuedtag.content_object, quartz)
  324. def test_generic_relation_to_inherited_child(self):
  325. # GenericRelations to models that use multi-table inheritance work.
  326. granite = ValuableRock.objects.create(name='granite', hardness=5)
  327. ValuableTaggedItem.objects.create(content_object=granite, tag="countertop", value=1)
  328. self.assertEqual(ValuableRock.objects.filter(tags__value=1).count(), 1)
  329. # We're generating a slightly inefficient query for tags__tag - we
  330. # first join ValuableRock -> TaggedItem -> ValuableTaggedItem, and then
  331. # we fetch tag by joining TaggedItem from ValuableTaggedItem. The last
  332. # join isn't necessary, as TaggedItem <-> ValuableTaggedItem is a
  333. # one-to-one join.
  334. self.assertEqual(ValuableRock.objects.filter(tags__tag="countertop").count(), 1)
  335. granite.delete() # deleting the rock should delete the related tag.
  336. self.assertEqual(ValuableTaggedItem.objects.count(), 0)
  337. def test_gfk_manager(self):
  338. # GenericForeignKey should not use the default manager (which may filter objects) #16048
  339. tailless = Gecko.objects.create(has_tail=False)
  340. tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
  341. self.assertEqual(tag.content_object, tailless)
  342. def test_subclasses_with_gen_rel(self):
  343. """
  344. Concrete model subclasses with generic relations work
  345. correctly (ticket 11263).
  346. """
  347. granite = Rock.objects.create(name='granite', hardness=5)
  348. TaggedItem.objects.create(content_object=granite, tag="countertop")
  349. self.assertEqual(Rock.objects.get(tags__tag="countertop"), granite)
  350. def test_subclasses_with_parent_gen_rel(self):
  351. """
  352. Generic relations on a base class (Vegetable) work correctly in
  353. subclasses (Carrot).
  354. """
  355. bear = Carrot.objects.create(name='carrot')
  356. TaggedItem.objects.create(content_object=bear, tag='orange')
  357. self.assertEqual(Carrot.objects.get(tags__tag='orange'), bear)
  358. def test_get_or_create(self):
  359. # get_or_create should work with virtual fields (content_object)
  360. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  361. tag, created = TaggedItem.objects.get_or_create(tag="shiny", defaults={'content_object': quartz})
  362. self.assertTrue(created)
  363. self.assertEqual(tag.tag, "shiny")
  364. self.assertEqual(tag.content_object.id, quartz.id)
  365. def test_update_or_create_defaults(self):
  366. # update_or_create should work with virtual fields (content_object)
  367. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  368. diamond = Mineral.objects.create(name="Diamond", hardness=7)
  369. tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': quartz})
  370. self.assertTrue(created)
  371. self.assertEqual(tag.content_object.id, quartz.id)
  372. tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': diamond})
  373. self.assertFalse(created)
  374. self.assertEqual(tag.content_object.id, diamond.id)
  375. def test_query_content_type(self):
  376. msg = "Field 'content_object' does not generate an automatic reverse relation"
  377. with self.assertRaisesMessage(FieldError, msg):
  378. TaggedItem.objects.get(content_object='')
  379. def test_unsaved_instance_on_generic_foreign_key(self):
  380. """
  381. Assigning an unsaved object to GenericForeignKey should raise an
  382. exception on model.save().
  383. """
  384. quartz = Mineral(name="Quartz", hardness=7)
  385. with self.assertRaises(IntegrityError):
  386. TaggedItem.objects.create(tag="shiny", content_object=quartz)
  387. def test_cache_invalidation_for_content_type_id(self):
  388. # Create a Vegetable and Mineral with the same id.
  389. new_id = max(Vegetable.objects.order_by('-id')[0].id,
  390. Mineral.objects.order_by('-id')[0].id) + 1
  391. broccoli = Vegetable.objects.create(id=new_id, name="Broccoli")
  392. diamond = Mineral.objects.create(id=new_id, name="Diamond", hardness=7)
  393. tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy")
  394. tag.content_type = ContentType.objects.get_for_model(diamond)
  395. self.assertEqual(tag.content_object, diamond)
  396. def test_cache_invalidation_for_object_id(self):
  397. broccoli = Vegetable.objects.create(name="Broccoli")
  398. cauliflower = Vegetable.objects.create(name="Cauliflower")
  399. tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy")
  400. tag.object_id = cauliflower.id
  401. self.assertEqual(tag.content_object, cauliflower)
  402. def test_assign_content_object_in_init(self):
  403. spinach = Vegetable(name="spinach")
  404. tag = TaggedItem(content_object=spinach)
  405. self.assertEqual(tag.content_object, spinach)
  406. def test_create_after_prefetch(self):
  407. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  408. self.assertSequenceEqual(platypus.tags.all(), [])
  409. weird_tag = platypus.tags.create(tag='weird')
  410. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  411. def test_add_after_prefetch(self):
  412. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  413. self.assertSequenceEqual(platypus.tags.all(), [])
  414. weird_tag = TaggedItem.objects.create(tag='weird', content_object=platypus)
  415. platypus.tags.add(weird_tag)
  416. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  417. def test_remove_after_prefetch(self):
  418. weird_tag = self.platypus.tags.create(tag='weird')
  419. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  420. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  421. platypus.tags.remove(weird_tag)
  422. self.assertSequenceEqual(platypus.tags.all(), [])
  423. def test_clear_after_prefetch(self):
  424. weird_tag = self.platypus.tags.create(tag='weird')
  425. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  426. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  427. platypus.tags.clear()
  428. self.assertSequenceEqual(platypus.tags.all(), [])
  429. def test_set_after_prefetch(self):
  430. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  431. self.assertSequenceEqual(platypus.tags.all(), [])
  432. furry_tag = TaggedItem.objects.create(tag='furry', content_object=platypus)
  433. platypus.tags.set([furry_tag])
  434. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  435. weird_tag = TaggedItem.objects.create(tag='weird', content_object=platypus)
  436. platypus.tags.set([weird_tag])
  437. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  438. def test_add_then_remove_after_prefetch(self):
  439. furry_tag = self.platypus.tags.create(tag='furry')
  440. platypus = Animal.objects.prefetch_related('tags').get(pk=self.platypus.pk)
  441. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  442. weird_tag = self.platypus.tags.create(tag='weird')
  443. platypus.tags.add(weird_tag)
  444. self.assertSequenceEqual(platypus.tags.all(), [furry_tag, weird_tag])
  445. platypus.tags.remove(weird_tag)
  446. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  447. def test_prefetch_related_different_content_types(self):
  448. TaggedItem.objects.create(content_object=self.platypus, tag='prefetch_tag_1')
  449. TaggedItem.objects.create(
  450. content_object=Vegetable.objects.create(name='Broccoli'),
  451. tag='prefetch_tag_2',
  452. )
  453. TaggedItem.objects.create(
  454. content_object=Animal.objects.create(common_name='Bear'),
  455. tag='prefetch_tag_3',
  456. )
  457. qs = TaggedItem.objects.filter(
  458. tag__startswith='prefetch_tag_',
  459. ).prefetch_related('content_object', 'content_object__tags')
  460. with self.assertNumQueries(4):
  461. tags = list(qs)
  462. for tag in tags:
  463. self.assertSequenceEqual(tag.content_object.tags.all(), [tag])
  464. def test_prefetch_related_custom_object_id(self):
  465. tiger = Animal.objects.create(common_name='tiger')
  466. cheetah = Animal.objects.create(common_name='cheetah')
  467. Comparison.objects.create(
  468. first_obj=cheetah, other_obj=tiger, comparative='faster',
  469. )
  470. Comparison.objects.create(
  471. first_obj=tiger, other_obj=cheetah, comparative='cooler',
  472. )
  473. qs = Comparison.objects.prefetch_related('first_obj__comparisons')
  474. for comparison in qs:
  475. self.assertSequenceEqual(comparison.first_obj.comparisons.all(), [comparison])
  476. class ProxyRelatedModelTest(TestCase):
  477. def test_default_behavior(self):
  478. """
  479. The default for for_concrete_model should be True
  480. """
  481. base = ForConcreteModelModel()
  482. base.obj = rel = ProxyRelatedModel.objects.create()
  483. base.save()
  484. base = ForConcreteModelModel.objects.get(pk=base.pk)
  485. rel = ConcreteRelatedModel.objects.get(pk=rel.pk)
  486. self.assertEqual(base.obj, rel)
  487. def test_works_normally(self):
  488. """
  489. When for_concrete_model is False, we should still be able to get
  490. an instance of the concrete class.
  491. """
  492. base = ForProxyModelModel()
  493. base.obj = rel = ConcreteRelatedModel.objects.create()
  494. base.save()
  495. base = ForProxyModelModel.objects.get(pk=base.pk)
  496. self.assertEqual(base.obj, rel)
  497. def test_proxy_is_returned(self):
  498. """
  499. Instances of the proxy should be returned when
  500. for_concrete_model is False.
  501. """
  502. base = ForProxyModelModel()
  503. base.obj = ProxyRelatedModel.objects.create()
  504. base.save()
  505. base = ForProxyModelModel.objects.get(pk=base.pk)
  506. self.assertIsInstance(base.obj, ProxyRelatedModel)
  507. def test_query(self):
  508. base = ForProxyModelModel()
  509. base.obj = rel = ConcreteRelatedModel.objects.create()
  510. base.save()
  511. self.assertEqual(rel, ConcreteRelatedModel.objects.get(bases__id=base.id))
  512. def test_query_proxy(self):
  513. base = ForProxyModelModel()
  514. base.obj = rel = ProxyRelatedModel.objects.create()
  515. base.save()
  516. self.assertEqual(rel, ProxyRelatedModel.objects.get(bases__id=base.id))
  517. def test_generic_relation(self):
  518. base = ForProxyModelModel()
  519. base.obj = ProxyRelatedModel.objects.create()
  520. base.save()
  521. base = ForProxyModelModel.objects.get(pk=base.pk)
  522. rel = ProxyRelatedModel.objects.get(pk=base.obj.pk)
  523. self.assertEqual(base, rel.bases.get())
  524. def test_generic_relation_set(self):
  525. base = ForProxyModelModel()
  526. base.obj = ConcreteRelatedModel.objects.create()
  527. base.save()
  528. newrel = ConcreteRelatedModel.objects.create()
  529. newrel.bases.set([base])
  530. newrel = ConcreteRelatedModel.objects.get(pk=newrel.pk)
  531. self.assertEqual(base, newrel.bases.get())
  532. class TestInitWithNoneArgument(SimpleTestCase):
  533. def test_none_allowed(self):
  534. # AllowsNullGFK doesn't require a content_type, so None argument should
  535. # also be allowed.
  536. AllowsNullGFK(content_object=None)
  537. # TaggedItem requires a content_type but initializing with None should
  538. # be allowed.
  539. TaggedItem(content_object=None)