Debian Codegraph @

tests/model_inheritance/tests.py

raw
1 from operator import attrgetter
2
3 from django.core.exceptions import FieldError, ValidationError
4 from django.db import connection, models
5 from django.db.models.query_utils import DeferredAttribute
6 from django.test import SimpleTestCase, TestCase
7 from django.test.utils import CaptureQueriesContext, isolate_apps
8
9 from .models import (
10 Base,
11 Chef,
12 CommonChild,
13 CommonInfo,
14 CustomSupplier,
15 GrandChild,
16 GrandParent,
17 ItalianRestaurant,
18 ItalianRestaurantCommonParent,
19 MixinModel,
20 Parent,
21 ParkingLot,
22 Place,
23 Post,
24 Restaurant,
25 Student,
26 SubBase,
27 Supplier,
28 Title,
29 Worker,
30 )
31
32
33 class ModelInheritanceTests(TestCase):
34 def test_abstract(self):
35 # The Student and Worker models both have 'name' and 'age' fields on
36 # them and inherit the __str__() method, just as with normal Python
37 # subclassing. This is useful if you want to factor out common
38 # information for programming purposes, but still completely
39 # independent separate models at the database level.
40 w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
41 Worker.objects.create(name="Barney", age=34, job="Quarry worker")
42
43 s = Student.objects.create(name="Pebbles", age=5, school_class="1B")
44
45 self.assertEqual(str(w1), "Worker Fred")
46 self.assertEqual(str(s), "Student Pebbles")
47
48 # The children inherit the Meta class of their parents (if they don't
49 # specify their own).
50 self.assertSequenceEqual(
51 Worker.objects.values("name"),
52 [
53 {"name": "Barney"},
54 {"name": "Fred"},
55 ],
56 )
57
58 # Since Student does not subclass CommonInfo's Meta, it has the effect
59 # of completely overriding it. So ordering by name doesn't take place
60 # for Students.
61 self.assertEqual(Student._meta.ordering, [])
62
63 # However, the CommonInfo class cannot be used as a normal model (it
64 # doesn't exist as a model).
65 with self.assertRaisesMessage(
66 AttributeError, "'CommonInfo' has no attribute 'objects'"
67 ):
68 CommonInfo.objects.all()
69
70 def test_reverse_relation_for_different_hierarchy_tree(self):
71 # Even though p.supplier for a Place 'p' (a parent of a Supplier), a
72 # Restaurant object cannot access that reverse relation, since it's not
73 # part of the Place-Supplier Hierarchy.
74 self.assertSequenceEqual(Place.objects.filter(supplier__name="foo"), [])
75 msg = (
76 "Cannot resolve keyword 'supplier' into field. Choices are: "
77 "address, chef, chef_id, id, italianrestaurant, lot, name, "
78 "place_ptr, place_ptr_id, provider, rating, serves_hot_dogs, serves_pizza"
79 )
80 with self.assertRaisesMessage(FieldError, msg):
81 Restaurant.objects.filter(supplier__name="foo")
82
83 def test_model_with_distinct_accessors(self):
84 # The Post model has distinct accessors for the Comment and Link models.
85 post = Post.objects.create(title="Lorem Ipsum")
86 post.attached_comment_set.create(content="Save $ on V1agr@", is_spam=True)
87 post.attached_link_set.create(
88 content="The web framework for perfections with deadlines.",
89 url="http://www.djangoproject.com/",
90 )
91
92 # The Post model doesn't have an attribute called
93 # 'attached_%(class)s_set'.
94 msg = "'Post' object has no attribute 'attached_%(class)s_set'"
95 with self.assertRaisesMessage(AttributeError, msg):
96 getattr(post, "attached_%(class)s_set")
97
98 def test_model_with_distinct_related_query_name(self):
99 self.assertSequenceEqual(
100 Post.objects.filter(attached_model_inheritance_comments__is_spam=True), []
101 )
102
103 # The Post model doesn't have a related query accessor based on
104 # related_name (attached_comment_set).
105 msg = "Cannot resolve keyword 'attached_comment_set' into field."
106 with self.assertRaisesMessage(FieldError, msg):
107 Post.objects.filter(attached_comment_set__is_spam=True)
108
109 def test_meta_fields_and_ordering(self):
110 # Make sure Restaurant and ItalianRestaurant have the right fields in
111 # the right order.
112 self.assertEqual(
113 [f.name for f in Restaurant._meta.fields],
114 [
115 "id",
116 "name",
117 "address",
118 "place_ptr",
119 "rating",
120 "serves_hot_dogs",
121 "serves_pizza",
122 "chef",
123 ],
124 )
125 self.assertEqual(
126 [f.name for f in ItalianRestaurant._meta.fields],
127 [
128 "id",
129 "name",
130 "address",
131 "place_ptr",
132 "rating",
133 "serves_hot_dogs",
134 "serves_pizza",
135 "chef",
136 "restaurant_ptr",
137 "serves_gnocchi",
138 ],
139 )
140 self.assertEqual(Restaurant._meta.ordering, ["-rating"])
141
142 def test_custompk_m2m(self):
143 b = Base.objects.create()
144 b.titles.add(Title.objects.create(title="foof"))
145 s = SubBase.objects.create(sub_id=b.id)
146 b = Base.objects.get(pk=s.id)
147 self.assertNotEqual(b.pk, s.pk)
148 # Low-level test for related_val
149 self.assertEqual(s.titles.related_val, (s.id,))
150 # Higher level test for correct query values (title foof not
151 # accidentally found).
152 self.assertSequenceEqual(s.titles.all(), [])
153
154 def test_create_diamond_mti_default_pk(self):
155 # 1 INSERT for each base.
156 with self.assertNumQueries(4):
157 common_child = CommonChild.objects.create()
158 # 3 SELECTs for the parents, 1 UPDATE for the child.
159 with self.assertNumQueries(4):
160 common_child.save()
161
162 def test_create_diamond_mti_common_parent(self):
163 with self.assertNumQueries(4):
164 italian_restaurant_child = ItalianRestaurantCommonParent.objects.create(
165 name="Ristorante Miron",
166 address="1234 W. Ash",
167 )
168
169 self.assertEqual(
170 italian_restaurant_child.italianrestaurant_ptr.place_ptr,
171 italian_restaurant_child.place_ptr_two,
172 )
173 self.assertEqual(
174 italian_restaurant_child.italianrestaurant_ptr.restaurant_ptr,
175 italian_restaurant_child.restaurant_ptr,
176 )
177 self.assertEqual(
178 italian_restaurant_child.restaurant_ptr.place_ptr,
179 italian_restaurant_child.place_ptr_two,
180 )
181 self.assertEqual(italian_restaurant_child.name, "Ristorante Miron")
182 self.assertEqual(italian_restaurant_child.address, "1234 W. Ash")
183
184 def test_update_parent_filtering(self):
185 """
186 Updating a field of a model subclass doesn't issue an UPDATE
187 query constrained by an inner query (#10399).
188 """
189 supplier = Supplier.objects.create(
190 name="Central market",
191 address="610 some street",
192 )
193 # Capture the expected query in a database agnostic way
194 with CaptureQueriesContext(connection) as captured_queries:
195 Place.objects.filter(pk=supplier.pk).update(name=supplier.name)
196 expected_sql = captured_queries[0]["sql"]
197 # Capture the queries executed when a subclassed model instance is saved.
198 with CaptureQueriesContext(connection) as captured_queries:
199 supplier.save(update_fields=("name",))
200 for query in captured_queries:
201 sql = query["sql"]
202 if "UPDATE" in sql:
203 self.assertEqual(expected_sql, sql)
204
205 def test_create_child_no_update(self):
206 """Creating a child with non-abstract parents only issues INSERTs."""
207
208 def a():
209 GrandChild.objects.create(
210 email="[email protected]",
211 first_name="grand",
212 last_name="parent",
213 )
214
215 def b():
216 GrandChild().save()
217
218 for i, test in enumerate([a, b]):
219 with (
220 self.subTest(i=i),
221 self.assertNumQueries(4),
222 CaptureQueriesContext(connection) as queries,
223 ):
224 test()
225 for query in queries:
226 sql = query["sql"]
227 self.assertIn("INSERT INTO", sql, sql)
228
229 def test_create_copy_with_inherited_m2m(self):
230 restaurant = Restaurant.objects.create()
231 supplier = CustomSupplier.objects.create(
232 name="Central market", address="944 W. Fullerton"
233 )
234 supplier.customers.set([restaurant])
235 old_customers = supplier.customers.all()
236 supplier.pk = None
237 supplier.id = None
238 supplier._state.adding = True
239 supplier.save()
240 supplier.customers.set(old_customers)
241 supplier = Supplier.objects.get(pk=supplier.pk)
242 self.assertCountEqual(supplier.customers.all(), old_customers)
243 self.assertSequenceEqual(supplier.customers.all(), [restaurant])
244
245 def test_eq(self):
246 # Equality doesn't transfer in multitable inheritance.
247 self.assertNotEqual(Place(id=1), Restaurant(id=1))
248 self.assertNotEqual(Restaurant(id=1), Place(id=1))
249
250 def test_mixin_init(self):
251 m = MixinModel()
252 self.assertEqual(m.other_attr, 1)
253
254 @isolate_apps("model_inheritance")
255 def test_abstract_parent_link(self):
256 class A(models.Model):
257 pass
258
259 class B(A):
260 a = models.OneToOneField("A", parent_link=True, on_delete=models.CASCADE)
261
262 class Meta:
263 abstract = True
264
265 class C(B):
266 pass
267
268 self.assertIs(C._meta.parents[A], C._meta.get_field("a"))
269
270 @isolate_apps("model_inheritance")
271 def test_init_subclass(self):
272 saved_kwargs = {}
273
274 class A(models.Model):
275 def __init_subclass__(cls, **kwargs):
276 super().__init_subclass__()
277 saved_kwargs.update(kwargs)
278
279 kwargs = {"x": 1, "y": 2, "z": 3}
280
281 class B(A, **kwargs):
282 pass
283
284 self.assertEqual(saved_kwargs, kwargs)
285
286 @isolate_apps("model_inheritance")
287 def test_set_name(self):
288 class ClassAttr:
289 called = None
290
291 def __set_name__(self_, owner, name):
292 self.assertIsNone(self_.called)
293 self_.called = (owner, name)
294
295 class A(models.Model):
296 attr = ClassAttr()
297
298 self.assertEqual(A.attr.called, (A, "attr"))
299
300 def test_inherited_ordering_pk_desc(self):
301 p1 = Parent.objects.create(first_name="Joe", email="[email protected]")
302 p2 = Parent.objects.create(first_name="Jon", email="[email protected]")
303 expected_order_by_sql = "ORDER BY %s.%s DESC" % (
304 connection.ops.quote_name(Parent._meta.db_table),
305 connection.ops.quote_name(Parent._meta.get_field("grandparent_ptr").column),
306 )
307 qs = Parent.objects.all()
308 self.assertSequenceEqual(qs, [p2, p1])
309 self.assertIn(expected_order_by_sql, str(qs.query))
310
311 def test_queryset_class_getitem(self):
312 self.assertIs(models.QuerySet[Post], models.QuerySet)
313 self.assertIs(models.QuerySet[Post, Post], models.QuerySet)
314 self.assertIs(models.QuerySet[Post, int, str], models.QuerySet)
315
316 def test_shadow_parent_attribute_with_field(self):
317 class ScalarParent(models.Model):
318 foo = 1
319
320 class ScalarOverride(ScalarParent):
321 foo = models.IntegerField()
322
323 self.assertEqual(type(ScalarOverride.foo), DeferredAttribute)
324
325 def test_shadow_parent_property_with_field(self):
326 class PropertyParent(models.Model):
327 @property
328 def foo(self):
329 pass
330
331 class PropertyOverride(PropertyParent):
332 foo = models.IntegerField()
333
334 self.assertEqual(type(PropertyOverride.foo), DeferredAttribute)
335
336 def test_shadow_parent_method_with_field(self):
337 class MethodParent(models.Model):
338 def foo(self):
339 pass
340
341 class MethodOverride(MethodParent):
342 foo = models.IntegerField()
343
344 self.assertEqual(type(MethodOverride.foo), DeferredAttribute)
345
346 def test_full_clean(self):
347 restaurant = Restaurant.objects.create()
348 with self.assertNumQueries(0), self.assertRaises(ValidationError):
349 restaurant.full_clean()
350
351
352 class ModelInheritanceDataTests(TestCase):
353 @classmethod
354 def setUpTestData(cls):
355 cls.restaurant = Restaurant.objects.create(
356 name="Demon Dogs",
357 address="944 W. Fullerton",
358 serves_hot_dogs=True,
359 serves_pizza=False,
360 rating=2,
361 )
362
363 chef = Chef.objects.create(name="Albert")
364 cls.italian_restaurant = ItalianRestaurant.objects.create(
365 name="Ristorante Miron",
366 address="1234 W. Ash",
367 serves_hot_dogs=False,
368 serves_pizza=False,
369 serves_gnocchi=True,
370 rating=4,
371 chef=chef,
372 )
373
374 def test_filter_inherited_model(self):
375 self.assertQuerySetEqual(
376 ItalianRestaurant.objects.filter(address="1234 W. Ash"),
377 [
378 "Ristorante Miron",
379 ],
380 attrgetter("name"),
381 )
382
383 def test_update_inherited_model(self):
384 self.italian_restaurant.address = "1234 W. Elm"
385 self.italian_restaurant.save()
386 self.assertQuerySetEqual(
387 ItalianRestaurant.objects.filter(address="1234 W. Elm"),
388 [
389 "Ristorante Miron",
390 ],
391 attrgetter("name"),
392 )
393
394 def test_parent_fields_available_for_filtering_in_child_model(self):
395 # Parent fields can be used directly in filters on the child model.
396 self.assertQuerySetEqual(
397 Restaurant.objects.filter(name="Demon Dogs"),
398 [
399 "Demon Dogs",
400 ],
401 attrgetter("name"),
402 )
403 self.assertQuerySetEqual(
404 ItalianRestaurant.objects.filter(address="1234 W. Ash"),
405 [
406 "Ristorante Miron",
407 ],
408 attrgetter("name"),
409 )
410
411 def test_filter_on_parent_returns_object_of_parent_type(self):
412 # Filters against the parent model return objects of the parent's type.
413 p = Place.objects.get(name="Demon Dogs")
414 self.assertIs(type(p), Place)
415
416 def test_parent_child_one_to_one_link(self):
417 # Since the parent and child are linked by an automatically created
418 # OneToOneField, you can get from the parent to the child by using the
419 # child's name.
420 self.assertEqual(
421 Place.objects.get(name="Demon Dogs").restaurant,
422 Restaurant.objects.get(name="Demon Dogs"),
423 )
424 self.assertEqual(
425 Place.objects.get(name="Ristorante Miron").restaurant.italianrestaurant,
426 ItalianRestaurant.objects.get(name="Ristorante Miron"),
427 )
428 self.assertEqual(
429 Restaurant.objects.get(name="Ristorante Miron").italianrestaurant,
430 ItalianRestaurant.objects.get(name="Ristorante Miron"),
431 )
432
433 def test_parent_child_one_to_one_link_on_nonrelated_objects(self):
434 # This won't work because the Demon Dogs restaurant is not an Italian
435 # restaurant.
436 with self.assertRaises(ItalianRestaurant.DoesNotExist):
437 Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
438
439 def test_inherited_does_not_exist_exception(self):
440 # An ItalianRestaurant which does not exist is also a Place which does
441 # not exist.
442 with self.assertRaises(Place.DoesNotExist):
443 ItalianRestaurant.objects.get(name="The Noodle Void")
444
445 def test_inherited_multiple_objects_returned_exception(self):
446 # MultipleObjectsReturned is also inherited.
447 with self.assertRaises(Place.MultipleObjectsReturned):
448 Restaurant.objects.get()
449
450 def test_related_objects_for_inherited_models(self):
451 # Related objects work just as they normally do.
452 s1 = Supplier.objects.create(name="Joe's Chickens", address="123 Sesame St")
453 s1.customers.set([self.restaurant, self.italian_restaurant])
454 s2 = Supplier.objects.create(name="Luigi's Pasta", address="456 Sesame St")
455 s2.customers.set([self.italian_restaurant])
456
457 # This won't work because the Place we select is not a Restaurant (it's
458 # a Supplier).
459 p = Place.objects.get(name="Joe's Chickens")
460 with self.assertRaises(Restaurant.DoesNotExist):
461 p.restaurant
462
463 self.assertEqual(p.supplier, s1)
464 self.assertQuerySetEqual(
465 self.italian_restaurant.provider.order_by("-name"),
466 ["Luigi's Pasta", "Joe's Chickens"],
467 attrgetter("name"),
468 )
469 self.assertQuerySetEqual(
470 Restaurant.objects.filter(provider__name__contains="Chickens"),
471 [
472 "Ristorante Miron",
473 "Demon Dogs",
474 ],
475 attrgetter("name"),
476 )
477 self.assertQuerySetEqual(
478 ItalianRestaurant.objects.filter(provider__name__contains="Chickens"),
479 [
480 "Ristorante Miron",
481 ],
482 attrgetter("name"),
483 )
484
485 ParkingLot.objects.create(name="Main St", address="111 Main St", main_site=s1)
486 ParkingLot.objects.create(
487 name="Well Lit", address="124 Sesame St", main_site=self.italian_restaurant
488 )
489
490 self.assertEqual(
491 Restaurant.objects.get(lot__name="Well Lit").name, "Ristorante Miron"
492 )
493
494 def test_update_works_on_parent_and_child_models_at_once(self):
495 # The update() command can update fields in parent and child classes at
496 # once (although it executed multiple SQL queries to do so).
497 rows = Restaurant.objects.filter(
498 serves_hot_dogs=True, name__contains="D"
499 ).update(name="Demon Puppies", serves_hot_dogs=False)
500 self.assertEqual(rows, 1)
501
502 r1 = Restaurant.objects.get(pk=self.restaurant.pk)
503 self.assertFalse(r1.serves_hot_dogs)
504 self.assertEqual(r1.name, "Demon Puppies")
505
506 def test_values_works_on_parent_model_fields(self):
507 # The values() command also works on fields from parent models.
508 self.assertSequenceEqual(
509 ItalianRestaurant.objects.values("name", "rating"),
510 [
511 {"rating": 4, "name": "Ristorante Miron"},
512 ],
513 )
514
515 def test_select_related_works_on_parent_model_fields(self):
516 # select_related works with fields from the parent object as if they
517 # were a normal part of the model.
518 self.assertNumQueries(2, lambda: ItalianRestaurant.objects.all()[0].chef)
519 self.assertNumQueries(
520 1, lambda: ItalianRestaurant.objects.select_related("chef")[0].chef
521 )
522
523 def test_select_related_defer(self):
524 """
525 #23370 - Should be able to defer child fields when using
526 select_related() from parent to child.
527 """
528 qs = (
529 Restaurant.objects.select_related("italianrestaurant")
530 .defer("italianrestaurant__serves_gnocchi")
531 .order_by("rating")
532 )
533
534 # The field was actually deferred
535 with self.assertNumQueries(2):
536 objs = list(qs.all())
537 self.assertTrue(objs[1].italianrestaurant.serves_gnocchi)
538
539 # Model fields where assigned correct values
540 self.assertEqual(qs[0].name, "Demon Dogs")
541 self.assertEqual(qs[0].rating, 2)
542 self.assertEqual(qs[1].italianrestaurant.name, "Ristorante Miron")
543 self.assertEqual(qs[1].italianrestaurant.rating, 4)
544
545 def test_parent_cache_reuse(self):
546 place = Place.objects.create()
547 GrandChild.objects.create(place=place)
548 grand_parent = GrandParent.objects.latest("pk")
549 with self.assertNumQueries(1):
550 self.assertEqual(grand_parent.place, place)
551 parent = grand_parent.parent
552 with self.assertNumQueries(0):
553 self.assertEqual(parent.place, place)
554 child = parent.child
555 with self.assertNumQueries(0):
556 self.assertEqual(child.place, place)
557 grandchild = child.grandchild
558 with self.assertNumQueries(0):
559 self.assertEqual(grandchild.place, place)
560
561 def test_update_query_counts(self):
562 """
563 Update queries do not generate unnecessary queries (#18304).
564 """
565 with self.assertNumQueries(3):
566 self.italian_restaurant.save()
567
568 def test_filter_inherited_on_null(self):
569 # Refs #12567
570 Supplier.objects.create(
571 name="Central market",
572 address="610 some street",
573 )
574 self.assertQuerySetEqual(
575 Place.objects.filter(supplier__isnull=False),
576 [
577 "Central market",
578 ],
579 attrgetter("name"),
580 )
581 self.assertQuerySetEqual(
582 Place.objects.filter(supplier__isnull=True).order_by("name"),
583 [
584 "Demon Dogs",
585 "Ristorante Miron",
586 ],
587 attrgetter("name"),
588 )
589
590 def test_exclude_inherited_on_null(self):
591 # Refs #12567
592 Supplier.objects.create(
593 name="Central market",
594 address="610 some street",
595 )
596 self.assertQuerySetEqual(
597 Place.objects.exclude(supplier__isnull=False).order_by("name"),
598 [
599 "Demon Dogs",
600 "Ristorante Miron",
601 ],
602 attrgetter("name"),
603 )
604 self.assertQuerySetEqual(
605 Place.objects.exclude(supplier__isnull=True),
606 [
607 "Central market",
608 ],
609 attrgetter("name"),
610 )
611
612
613 @isolate_apps("model_inheritance", "model_inheritance.tests")
614 class InheritanceSameModelNameTests(SimpleTestCase):
615 def test_abstract_fk_related_name(self):
616 related_name = "%(app_label)s_%(class)s_references"
617
618 class Referenced(models.Model):
619 class Meta:
620 app_label = "model_inheritance"
621
622 class AbstractReferent(models.Model):
623 reference = models.ForeignKey(
624 Referenced, models.CASCADE, related_name=related_name
625 )
626
627 class Meta:
628 app_label = "model_inheritance"
629 abstract = True
630
631 class Referent(AbstractReferent):
632 class Meta:
633 app_label = "model_inheritance"
634
635 LocalReferent = Referent
636
637 class Referent(AbstractReferent):
638 class Meta:
639 app_label = "tests"
640
641 ForeignReferent = Referent
642
643 self.assertFalse(hasattr(Referenced, related_name))
644 self.assertIs(
645 Referenced.model_inheritance_referent_references.field.model, LocalReferent
646 )
647 self.assertIs(Referenced.tests_referent_references.field.model, ForeignReferent)
648
649
650 class InheritanceUniqueTests(TestCase):
651 @classmethod
652 def setUpTestData(cls):
653 cls.grand_parent = GrandParent.objects.create(
654 email="[email protected]",
655 first_name="grand",
656 last_name="parent",
657 )
658
659 def test_unique(self):
660 grand_child = GrandChild(
661 email=self.grand_parent.email,
662 first_name="grand",
663 last_name="child",
664 )
665 msg = "Grand parent with this Email already exists."
666 with self.assertRaisesMessage(ValidationError, msg):
667 grand_child.validate_unique()
668
669 def test_unique_together(self):
670 grand_child = GrandChild(
671 email="[email protected]",
672 first_name=self.grand_parent.first_name,
673 last_name=self.grand_parent.last_name,
674 )
675 msg = "Grand parent with this First name and Last name already exists."
676 with self.assertRaisesMessage(ValidationError, msg):
677 grand_child.validate_unique()