Debian Codegraph @

tests/generic_relations/tests.py

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