tests.py 29 KB

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