tests.py 33 KB

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