2
0

tests.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. async def test_aadd(self):
  292. bacon = await Vegetable.objects.acreate(name="Bacon", is_yucky=False)
  293. t1 = await TaggedItem.objects.acreate(content_object=self.quartz, tag="shiny")
  294. t2 = await TaggedItem.objects.acreate(content_object=self.quartz, tag="fatty")
  295. await bacon.tags.aadd(t1, t2, bulk=False)
  296. self.assertEqual(await bacon.tags.acount(), 2)
  297. def test_set(self):
  298. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  299. fatty = bacon.tags.create(tag="fatty")
  300. salty = bacon.tags.create(tag="salty")
  301. bacon.tags.set([fatty, salty])
  302. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  303. bacon.tags.set([fatty])
  304. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  305. bacon.tags.set([])
  306. self.assertSequenceEqual(bacon.tags.all(), [])
  307. bacon.tags.set([fatty, salty], bulk=False, clear=True)
  308. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  309. bacon.tags.set([fatty], bulk=False, clear=True)
  310. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  311. bacon.tags.set([], clear=True)
  312. self.assertSequenceEqual(bacon.tags.all(), [])
  313. async def test_aset(self):
  314. bacon = await Vegetable.objects.acreate(name="Bacon", is_yucky=False)
  315. fatty = await bacon.tags.acreate(tag="fatty")
  316. await bacon.tags.aset([fatty])
  317. self.assertEqual(await bacon.tags.acount(), 1)
  318. await bacon.tags.aset([])
  319. self.assertEqual(await bacon.tags.acount(), 0)
  320. await bacon.tags.aset([fatty], bulk=False, clear=True)
  321. self.assertEqual(await bacon.tags.acount(), 1)
  322. def test_assign(self):
  323. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  324. fatty = bacon.tags.create(tag="fatty")
  325. salty = bacon.tags.create(tag="salty")
  326. bacon.tags.set([fatty, salty])
  327. self.assertSequenceEqual(bacon.tags.all(), [fatty, salty])
  328. bacon.tags.set([fatty])
  329. self.assertSequenceEqual(bacon.tags.all(), [fatty])
  330. bacon.tags.set([])
  331. self.assertSequenceEqual(bacon.tags.all(), [])
  332. def test_assign_with_queryset(self):
  333. # Querysets used in reverse GFK assignments are pre-evaluated so their
  334. # value isn't affected by the clearing operation
  335. # in ManyRelatedManager.set() (#19816).
  336. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  337. bacon.tags.create(tag="fatty")
  338. bacon.tags.create(tag="salty")
  339. self.assertEqual(2, bacon.tags.count())
  340. qs = bacon.tags.filter(tag="fatty")
  341. bacon.tags.set(qs)
  342. self.assertEqual(1, bacon.tags.count())
  343. self.assertEqual(1, qs.count())
  344. def test_clear(self):
  345. self.assertSequenceEqual(
  346. TaggedItem.objects.order_by("tag"),
  347. [self.fatty, self.hairy, self.salty, self.yellow],
  348. )
  349. self.bacon.tags.clear()
  350. self.assertSequenceEqual(self.bacon.tags.all(), [])
  351. self.assertSequenceEqual(
  352. TaggedItem.objects.order_by("tag"),
  353. [self.hairy, self.yellow],
  354. )
  355. async def test_aclear(self):
  356. await self.bacon.tags.aclear()
  357. self.assertEqual(await self.bacon.tags.acount(), 0)
  358. def test_remove(self):
  359. self.assertSequenceEqual(
  360. TaggedItem.objects.order_by("tag"),
  361. [self.fatty, self.hairy, self.salty, self.yellow],
  362. )
  363. self.bacon.tags.remove(self.fatty)
  364. self.assertSequenceEqual(self.bacon.tags.all(), [self.salty])
  365. self.assertSequenceEqual(
  366. TaggedItem.objects.order_by("tag"),
  367. [self.hairy, self.salty, self.yellow],
  368. )
  369. async def test_aremove(self):
  370. await self.bacon.tags.aremove(self.fatty)
  371. self.assertEqual(await self.bacon.tags.acount(), 1)
  372. await self.bacon.tags.aremove(self.salty)
  373. self.assertEqual(await self.bacon.tags.acount(), 0)
  374. def test_generic_relation_related_name_default(self):
  375. # GenericRelation isn't usable from the reverse side by default.
  376. msg = (
  377. "Cannot resolve keyword 'vegetable' into field. Choices are: "
  378. "animal, content_object, content_type, content_type_id, id, "
  379. "manualpk, object_id, tag, valuabletaggeditem"
  380. )
  381. with self.assertRaisesMessage(FieldError, msg):
  382. TaggedItem.objects.filter(vegetable__isnull=True)
  383. def test_multiple_gfk(self):
  384. # Simple tests for multiple GenericForeignKeys
  385. # only uses one model, since the above tests should be sufficient.
  386. tiger = Animal.objects.create(common_name="tiger")
  387. cheetah = Animal.objects.create(common_name="cheetah")
  388. bear = Animal.objects.create(common_name="bear")
  389. # Create directly
  390. c1 = Comparison.objects.create(
  391. first_obj=cheetah, other_obj=tiger, comparative="faster"
  392. )
  393. c2 = Comparison.objects.create(
  394. first_obj=tiger, other_obj=cheetah, comparative="cooler"
  395. )
  396. # Create using GenericRelation
  397. c3 = tiger.comparisons.create(other_obj=bear, comparative="cooler")
  398. c4 = tiger.comparisons.create(other_obj=cheetah, comparative="stronger")
  399. self.assertSequenceEqual(cheetah.comparisons.all(), [c1])
  400. # Filtering works
  401. self.assertCountEqual(
  402. tiger.comparisons.filter(comparative="cooler"),
  403. [c2, c3],
  404. )
  405. # Filtering and deleting works
  406. subjective = ["cooler"]
  407. tiger.comparisons.filter(comparative__in=subjective).delete()
  408. self.assertCountEqual(Comparison.objects.all(), [c1, c4])
  409. # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be
  410. # deleted since Animal has an explicit GenericRelation to Comparison
  411. # through first_obj. Comparisons with cheetah as 'other_obj' will not
  412. # be deleted.
  413. cheetah.delete()
  414. self.assertSequenceEqual(Comparison.objects.all(), [c4])
  415. def test_gfk_subclasses(self):
  416. # GenericForeignKey should work with subclasses (see #8309)
  417. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  418. valuedtag = ValuableTaggedItem.objects.create(
  419. content_object=quartz, tag="shiny", value=10
  420. )
  421. self.assertEqual(valuedtag.content_object, quartz)
  422. def test_generic_relation_to_inherited_child(self):
  423. # GenericRelations to models that use multi-table inheritance work.
  424. granite = ValuableRock.objects.create(name="granite", hardness=5)
  425. ValuableTaggedItem.objects.create(
  426. content_object=granite, tag="countertop", value=1
  427. )
  428. self.assertEqual(ValuableRock.objects.filter(tags__value=1).count(), 1)
  429. # We're generating a slightly inefficient query for tags__tag - we
  430. # first join ValuableRock -> TaggedItem -> ValuableTaggedItem, and then
  431. # we fetch tag by joining TaggedItem from ValuableTaggedItem. The last
  432. # join isn't necessary, as TaggedItem <-> ValuableTaggedItem is a
  433. # one-to-one join.
  434. self.assertEqual(ValuableRock.objects.filter(tags__tag="countertop").count(), 1)
  435. granite.delete() # deleting the rock should delete the related tag.
  436. self.assertEqual(ValuableTaggedItem.objects.count(), 0)
  437. def test_gfk_manager(self):
  438. # GenericForeignKey should not use the default manager (which may
  439. # filter objects).
  440. tailless = Gecko.objects.create(has_tail=False)
  441. tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
  442. self.assertEqual(tag.content_object, tailless)
  443. def test_subclasses_with_gen_rel(self):
  444. """
  445. Concrete model subclasses with generic relations work
  446. correctly (ticket 11263).
  447. """
  448. granite = Rock.objects.create(name="granite", hardness=5)
  449. TaggedItem.objects.create(content_object=granite, tag="countertop")
  450. self.assertEqual(Rock.objects.get(tags__tag="countertop"), granite)
  451. def test_subclasses_with_parent_gen_rel(self):
  452. """
  453. Generic relations on a base class (Vegetable) work correctly in
  454. subclasses (Carrot).
  455. """
  456. bear = Carrot.objects.create(name="carrot")
  457. TaggedItem.objects.create(content_object=bear, tag="orange")
  458. self.assertEqual(Carrot.objects.get(tags__tag="orange"), bear)
  459. def test_get_or_create(self):
  460. # get_or_create should work with virtual fields (content_object)
  461. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  462. tag, created = TaggedItem.objects.get_or_create(
  463. tag="shiny", defaults={"content_object": quartz}
  464. )
  465. self.assertTrue(created)
  466. self.assertEqual(tag.tag, "shiny")
  467. self.assertEqual(tag.content_object.id, quartz.id)
  468. def test_update_or_create_defaults(self):
  469. # update_or_create should work with virtual fields (content_object)
  470. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  471. diamond = Mineral.objects.create(name="Diamond", hardness=7)
  472. tag, created = TaggedItem.objects.update_or_create(
  473. tag="shiny", defaults={"content_object": quartz}
  474. )
  475. self.assertTrue(created)
  476. self.assertEqual(tag.content_object.id, quartz.id)
  477. tag, created = TaggedItem.objects.update_or_create(
  478. tag="shiny", defaults={"content_object": diamond}
  479. )
  480. self.assertFalse(created)
  481. self.assertEqual(tag.content_object.id, diamond.id)
  482. def test_query_content_type(self):
  483. msg = "Field 'content_object' does not generate an automatic reverse relation"
  484. with self.assertRaisesMessage(FieldError, msg):
  485. TaggedItem.objects.get(content_object="")
  486. def test_unsaved_generic_foreign_key_parent_save(self):
  487. quartz = Mineral(name="Quartz", hardness=7)
  488. tagged_item = TaggedItem(tag="shiny", content_object=quartz)
  489. msg = (
  490. "save() prohibited to prevent data loss due to unsaved related object "
  491. "'content_object'."
  492. )
  493. with self.assertRaisesMessage(ValueError, msg):
  494. tagged_item.save()
  495. @skipUnlessDBFeature("has_bulk_insert")
  496. def test_unsaved_generic_foreign_key_parent_bulk_create(self):
  497. quartz = Mineral(name="Quartz", hardness=7)
  498. tagged_item = TaggedItem(tag="shiny", content_object=quartz)
  499. msg = (
  500. "bulk_create() prohibited to prevent data loss due to unsaved related "
  501. "object 'content_object'."
  502. )
  503. with self.assertRaisesMessage(ValueError, msg):
  504. TaggedItem.objects.bulk_create([tagged_item])
  505. def test_cache_invalidation_for_content_type_id(self):
  506. # Create a Vegetable and Mineral with the same id.
  507. new_id = (
  508. max(
  509. Vegetable.objects.order_by("-id")[0].id,
  510. Mineral.objects.order_by("-id")[0].id,
  511. )
  512. + 1
  513. )
  514. broccoli = Vegetable.objects.create(id=new_id, name="Broccoli")
  515. diamond = Mineral.objects.create(id=new_id, name="Diamond", hardness=7)
  516. tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy")
  517. tag.content_type = ContentType.objects.get_for_model(diamond)
  518. self.assertEqual(tag.content_object, diamond)
  519. def test_cache_invalidation_for_object_id(self):
  520. broccoli = Vegetable.objects.create(name="Broccoli")
  521. cauliflower = Vegetable.objects.create(name="Cauliflower")
  522. tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy")
  523. tag.object_id = cauliflower.id
  524. self.assertEqual(tag.content_object, cauliflower)
  525. def test_assign_content_object_in_init(self):
  526. spinach = Vegetable(name="spinach")
  527. tag = TaggedItem(content_object=spinach)
  528. self.assertEqual(tag.content_object, spinach)
  529. def test_create_after_prefetch(self):
  530. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  531. self.assertSequenceEqual(platypus.tags.all(), [])
  532. weird_tag = platypus.tags.create(tag="weird")
  533. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  534. def test_add_after_prefetch(self):
  535. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  536. self.assertSequenceEqual(platypus.tags.all(), [])
  537. weird_tag = TaggedItem.objects.create(tag="weird", content_object=platypus)
  538. platypus.tags.add(weird_tag)
  539. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  540. def test_remove_after_prefetch(self):
  541. weird_tag = self.platypus.tags.create(tag="weird")
  542. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  543. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  544. platypus.tags.remove(weird_tag)
  545. self.assertSequenceEqual(platypus.tags.all(), [])
  546. def test_clear_after_prefetch(self):
  547. weird_tag = self.platypus.tags.create(tag="weird")
  548. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  549. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  550. platypus.tags.clear()
  551. self.assertSequenceEqual(platypus.tags.all(), [])
  552. def test_set_after_prefetch(self):
  553. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  554. self.assertSequenceEqual(platypus.tags.all(), [])
  555. furry_tag = TaggedItem.objects.create(tag="furry", content_object=platypus)
  556. platypus.tags.set([furry_tag])
  557. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  558. weird_tag = TaggedItem.objects.create(tag="weird", content_object=platypus)
  559. platypus.tags.set([weird_tag])
  560. self.assertSequenceEqual(platypus.tags.all(), [weird_tag])
  561. def test_add_then_remove_after_prefetch(self):
  562. furry_tag = self.platypus.tags.create(tag="furry")
  563. platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk)
  564. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  565. weird_tag = self.platypus.tags.create(tag="weird")
  566. platypus.tags.add(weird_tag)
  567. self.assertSequenceEqual(platypus.tags.all(), [furry_tag, weird_tag])
  568. platypus.tags.remove(weird_tag)
  569. self.assertSequenceEqual(platypus.tags.all(), [furry_tag])
  570. def test_prefetch_related_different_content_types(self):
  571. TaggedItem.objects.create(content_object=self.platypus, tag="prefetch_tag_1")
  572. TaggedItem.objects.create(
  573. content_object=Vegetable.objects.create(name="Broccoli"),
  574. tag="prefetch_tag_2",
  575. )
  576. TaggedItem.objects.create(
  577. content_object=Animal.objects.create(common_name="Bear"),
  578. tag="prefetch_tag_3",
  579. )
  580. qs = TaggedItem.objects.filter(
  581. tag__startswith="prefetch_tag_",
  582. ).prefetch_related("content_object", "content_object__tags")
  583. with self.assertNumQueries(4):
  584. tags = list(qs)
  585. for tag in tags:
  586. self.assertSequenceEqual(tag.content_object.tags.all(), [tag])
  587. def test_prefetch_related_custom_object_id(self):
  588. tiger = Animal.objects.create(common_name="tiger")
  589. cheetah = Animal.objects.create(common_name="cheetah")
  590. Comparison.objects.create(
  591. first_obj=cheetah,
  592. other_obj=tiger,
  593. comparative="faster",
  594. )
  595. Comparison.objects.create(
  596. first_obj=tiger,
  597. other_obj=cheetah,
  598. comparative="cooler",
  599. )
  600. qs = Comparison.objects.prefetch_related("first_obj__comparisons")
  601. for comparison in qs:
  602. self.assertSequenceEqual(
  603. comparison.first_obj.comparisons.all(), [comparison]
  604. )
  605. class ProxyRelatedModelTest(TestCase):
  606. def test_default_behavior(self):
  607. """
  608. The default for for_concrete_model should be True
  609. """
  610. base = ForConcreteModelModel()
  611. base.obj = rel = ProxyRelatedModel.objects.create()
  612. base.save()
  613. base = ForConcreteModelModel.objects.get(pk=base.pk)
  614. rel = ConcreteRelatedModel.objects.get(pk=rel.pk)
  615. self.assertEqual(base.obj, rel)
  616. def test_works_normally(self):
  617. """
  618. When for_concrete_model is False, we should still be able to get
  619. an instance of the concrete class.
  620. """
  621. base = ForProxyModelModel()
  622. base.obj = rel = ConcreteRelatedModel.objects.create()
  623. base.save()
  624. base = ForProxyModelModel.objects.get(pk=base.pk)
  625. self.assertEqual(base.obj, rel)
  626. def test_proxy_is_returned(self):
  627. """
  628. Instances of the proxy should be returned when
  629. for_concrete_model is False.
  630. """
  631. base = ForProxyModelModel()
  632. base.obj = ProxyRelatedModel.objects.create()
  633. base.save()
  634. base = ForProxyModelModel.objects.get(pk=base.pk)
  635. self.assertIsInstance(base.obj, ProxyRelatedModel)
  636. def test_query(self):
  637. base = ForProxyModelModel()
  638. base.obj = rel = ConcreteRelatedModel.objects.create()
  639. base.save()
  640. self.assertEqual(rel, ConcreteRelatedModel.objects.get(bases__id=base.id))
  641. def test_query_proxy(self):
  642. base = ForProxyModelModel()
  643. base.obj = rel = ProxyRelatedModel.objects.create()
  644. base.save()
  645. self.assertEqual(rel, ProxyRelatedModel.objects.get(bases__id=base.id))
  646. def test_generic_relation(self):
  647. base = ForProxyModelModel()
  648. base.obj = ProxyRelatedModel.objects.create()
  649. base.save()
  650. base = ForProxyModelModel.objects.get(pk=base.pk)
  651. rel = ProxyRelatedModel.objects.get(pk=base.obj.pk)
  652. self.assertEqual(base, rel.bases.get())
  653. def test_generic_relation_set(self):
  654. base = ForProxyModelModel()
  655. base.obj = ConcreteRelatedModel.objects.create()
  656. base.save()
  657. newrel = ConcreteRelatedModel.objects.create()
  658. newrel.bases.set([base])
  659. newrel = ConcreteRelatedModel.objects.get(pk=newrel.pk)
  660. self.assertEqual(base, newrel.bases.get())
  661. class TestInitWithNoneArgument(SimpleTestCase):
  662. def test_none_allowed(self):
  663. # AllowsNullGFK doesn't require a content_type, so None argument should
  664. # also be allowed.
  665. AllowsNullGFK(content_object=None)
  666. # TaggedItem requires a content_type but initializing with None should
  667. # be allowed.
  668. TaggedItem(content_object=None)