Debian Codegraph @

tests/model_inheritance_regress/tests.py

raw
1 """
2 Regression tests for Model inheritance behavior.
3 """
4
5 import datetime
6 from operator import attrgetter
7 from unittest import expectedFailure
8
9 from django import forms
10 from django.test import TestCase
11
12 from .models import (
13 ArticleWithAuthor,
14 BachelorParty,
15 BirthdayParty,
16 BusStation,
17 Child,
18 Congressman,
19 DerivedM,
20 InternalCertificationAudit,
21 ItalianRestaurant,
22 M2MChild,
23 MessyBachelorParty,
24 ParkingLot,
25 ParkingLot3,
26 ParkingLot4A,
27 ParkingLot4B,
28 Person,
29 Place,
30 Politician,
31 Profile,
32 QualityControl,
33 Restaurant,
34 SelfRefChild,
35 SelfRefParent,
36 Senator,
37 Supplier,
38 TrainStation,
39 User,
40 Wholesaler,
41 )
42
43
44 class ModelInheritanceTest(TestCase):
45 def test_model_inheritance(self):
46 # Regression for #7350, #7202
47 # When you create a Parent object with a specific reference to an
48 # existent child instance, saving the Parent doesn't duplicate the
49 # child. This behavior is only activated during a raw save - it is
50 # mostly relevant to deserialization, but any sort of CORBA style
51 # 'narrow()' API would require a similar approach.
52
53 # Create a child-parent-grandparent chain
54 place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton")
55 place1.save_base(raw=True)
56 restaurant = Restaurant(
57 place_ptr=place1,
58 serves_hot_dogs=True,
59 serves_pizza=False,
60 )
61 restaurant.save_base(raw=True)
62 italian_restaurant = ItalianRestaurant(
63 restaurant_ptr=restaurant, serves_gnocchi=True
64 )
65 italian_restaurant.save_base(raw=True)
66
67 # Create a child-parent chain with an explicit parent link
68 place2 = Place(name="Main St", address="111 Main St")
69 place2.save_base(raw=True)
70 park = ParkingLot(parent=place2, capacity=100)
71 park.save_base(raw=True)
72
73 # No extra parent objects have been created.
74 places = list(Place.objects.all())
75 self.assertEqual(places, [place1, place2])
76
77 dicts = list(Restaurant.objects.values("name", "serves_hot_dogs"))
78 self.assertEqual(
79 dicts, [{"name": "Guido's House of Pasta", "serves_hot_dogs": True}]
80 )
81
82 dicts = list(
83 ItalianRestaurant.objects.values(
84 "name", "serves_hot_dogs", "serves_gnocchi"
85 )
86 )
87 self.assertEqual(
88 dicts,
89 [
90 {
91 "name": "Guido's House of Pasta",
92 "serves_gnocchi": True,
93 "serves_hot_dogs": True,
94 }
95 ],
96 )
97
98 dicts = list(ParkingLot.objects.values("name", "capacity"))
99 self.assertEqual(
100 dicts,
101 [
102 {
103 "capacity": 100,
104 "name": "Main St",
105 }
106 ],
107 )
108
109 # You can also update objects when using a raw save.
110 place1.name = "Guido's All New House of Pasta"
111 place1.save_base(raw=True)
112
113 restaurant.serves_hot_dogs = False
114 restaurant.save_base(raw=True)
115
116 italian_restaurant.serves_gnocchi = False
117 italian_restaurant.save_base(raw=True)
118
119 place2.name = "Derelict lot"
120 place2.save_base(raw=True)
121
122 park.capacity = 50
123 park.save_base(raw=True)
124
125 # No extra parent objects after an update, either.
126 places = list(Place.objects.all())
127 self.assertEqual(places, [place2, place1])
128 self.assertEqual(places[0].name, "Derelict lot")
129 self.assertEqual(places[1].name, "Guido's All New House of Pasta")
130
131 dicts = list(Restaurant.objects.values("name", "serves_hot_dogs"))
132 self.assertEqual(
133 dicts,
134 [
135 {
136 "name": "Guido's All New House of Pasta",
137 "serves_hot_dogs": False,
138 }
139 ],
140 )
141
142 dicts = list(
143 ItalianRestaurant.objects.values(
144 "name", "serves_hot_dogs", "serves_gnocchi"
145 )
146 )
147 self.assertEqual(
148 dicts,
149 [
150 {
151 "name": "Guido's All New House of Pasta",
152 "serves_gnocchi": False,
153 "serves_hot_dogs": False,
154 }
155 ],
156 )
157
158 dicts = list(ParkingLot.objects.values("name", "capacity"))
159 self.assertEqual(
160 dicts,
161 [
162 {
163 "capacity": 50,
164 "name": "Derelict lot",
165 }
166 ],
167 )
168
169 # If you try to raw_save a parent attribute onto a child object,
170 # the attribute will be ignored.
171
172 italian_restaurant.name = "Lorenzo's Pasta Hut"
173 italian_restaurant.save_base(raw=True)
174
175 # Note that the name has not changed
176 # - name is an attribute of Place, not ItalianRestaurant
177 dicts = list(
178 ItalianRestaurant.objects.values(
179 "name", "serves_hot_dogs", "serves_gnocchi"
180 )
181 )
182 self.assertEqual(
183 dicts,
184 [
185 {
186 "name": "Guido's All New House of Pasta",
187 "serves_gnocchi": False,
188 "serves_hot_dogs": False,
189 }
190 ],
191 )
192
193 def test_issue_7105(self):
194 # Regressions tests for #7105: dates() queries should be able to use
195 # fields from the parent model as easily as the child.
196 Child.objects.create(
197 name="child", created=datetime.datetime(2008, 6, 26, 17, 0, 0)
198 )
199 datetimes = list(Child.objects.datetimes("created", "month"))
200 self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)])
201
202 def test_issue_7276(self):
203 # Regression test for #7276: calling delete() on a model with
204 # multi-table inheritance should delete the associated rows from any
205 # ancestor tables, as well as any descendent objects.
206 place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton")
207 place1.save_base(raw=True)
208 restaurant = Restaurant(
209 place_ptr=place1,
210 serves_hot_dogs=True,
211 serves_pizza=False,
212 )
213 restaurant.save_base(raw=True)
214 italian_restaurant = ItalianRestaurant(
215 restaurant_ptr=restaurant, serves_gnocchi=True
216 )
217 italian_restaurant.save_base(raw=True)
218
219 ident = ItalianRestaurant.objects.all()[0].id
220 self.assertEqual(Place.objects.get(pk=ident), place1)
221 Restaurant.objects.create(
222 name="a",
223 address="xx",
224 serves_hot_dogs=True,
225 serves_pizza=False,
226 )
227
228 # This should delete both Restaurants, plus the related places, plus
229 # the ItalianRestaurant.
230 Restaurant.objects.all().delete()
231
232 with self.assertRaises(Place.DoesNotExist):
233 Place.objects.get(pk=ident)
234 with self.assertRaises(ItalianRestaurant.DoesNotExist):
235 ItalianRestaurant.objects.get(pk=ident)
236
237 def test_issue_6755(self):
238 """
239 Regression test for #6755
240 """
241 r = Restaurant(serves_pizza=False, serves_hot_dogs=False)
242 r.save()
243 self.assertEqual(r.id, r.place_ptr_id)
244 orig_id = r.id
245 r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False)
246 r.save()
247 self.assertEqual(r.id, orig_id)
248 self.assertEqual(r.id, r.place_ptr_id)
249
250 def test_issue_11764(self):
251 """
252 Regression test for #11764
253 """
254 wholesalers = list(Wholesaler.objects.select_related())
255 self.assertEqual(wholesalers, [])
256
257 def test_issue_7853(self):
258 """
259 Regression test for #7853
260 If the parent class has a self-referential link, make sure that any
261 updates to that link via the child update the right table.
262 """
263 obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
264 obj.delete()
265
266 def test_get_next_previous_by_date(self):
267 """
268 Regression tests for #8076
269 get_(next/previous)_by_date should work
270 """
271 c1 = ArticleWithAuthor(
272 headline="ArticleWithAuthor 1",
273 author="Person 1",
274 pub_date=datetime.datetime(2005, 8, 1, 3, 0),
275 )
276 c1.save()
277 c2 = ArticleWithAuthor(
278 headline="ArticleWithAuthor 2",
279 author="Person 2",
280 pub_date=datetime.datetime(2005, 8, 1, 10, 0),
281 )
282 c2.save()
283 c3 = ArticleWithAuthor(
284 headline="ArticleWithAuthor 3",
285 author="Person 3",
286 pub_date=datetime.datetime(2005, 8, 2),
287 )
288 c3.save()
289
290 self.assertEqual(c1.get_next_by_pub_date(), c2)
291 self.assertEqual(c2.get_next_by_pub_date(), c3)
292 with self.assertRaises(ArticleWithAuthor.DoesNotExist):
293 c3.get_next_by_pub_date()
294 self.assertEqual(c3.get_previous_by_pub_date(), c2)
295 self.assertEqual(c2.get_previous_by_pub_date(), c1)
296 with self.assertRaises(ArticleWithAuthor.DoesNotExist):
297 c1.get_previous_by_pub_date()
298
299 def test_inherited_fields(self):
300 """
301 Regression test for #8825 and #9390
302 Make sure all inherited fields (esp. m2m fields, in this case) appear
303 on the child class.
304 """
305 m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
306 self.assertEqual(m2mchildren, [])
307
308 # Ordering should not include any database column more than once (this
309 # is most likely to occur naturally with model inheritance, so we
310 # check it here). Regression test for #9390. This necessarily pokes at
311 # the SQL string for the query, since the duplicate problems are only
312 # apparent at that late stage.
313 qs = ArticleWithAuthor.objects.order_by("pub_date", "pk")
314 sql = qs.query.get_compiler(qs.db).as_sql()[0]
315 fragment = sql[sql.find("ORDER BY") :]
316 pos = fragment.find("pub_date")
317 self.assertEqual(fragment.find("pub_date", pos + 1), -1)
318
319 def test_queryset_update_on_parent_model(self):
320 """
321 Regression test for #10362
322 It is possible to call update() and only change a field in
323 an ancestor model.
324 """
325 article = ArticleWithAuthor.objects.create(
326 author="fred",
327 headline="Hey there!",
328 pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0),
329 )
330 update = ArticleWithAuthor.objects.filter(author="fred").update(
331 headline="Oh, no!"
332 )
333 self.assertEqual(update, 1)
334 update = ArticleWithAuthor.objects.filter(pk=article.pk).update(
335 headline="Oh, no!"
336 )
337 self.assertEqual(update, 1)
338
339 derivedm1 = DerivedM.objects.create(
340 customPK=44,
341 base_name="b1",
342 derived_name="d1",
343 )
344 self.assertEqual(derivedm1.customPK, 44)
345 self.assertEqual(derivedm1.base_name, "b1")
346 self.assertEqual(derivedm1.derived_name, "d1")
347 derivedms = list(DerivedM.objects.all())
348 self.assertEqual(derivedms, [derivedm1])
349
350 def test_use_explicit_o2o_to_parent_as_pk(self):
351 """
352 The connector from child to parent need not be the pk on the child.
353 """
354 self.assertEqual(ParkingLot3._meta.pk.name, "primary_key")
355 # the child->parent link
356 self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, "parent")
357
358 def test_use_explicit_o2o_to_parent_from_abstract_model(self):
359 self.assertEqual(ParkingLot4A._meta.pk.name, "parent")
360 ParkingLot4A.objects.create(
361 name="Parking4A",
362 address="21 Jump Street",
363 )
364
365 self.assertEqual(ParkingLot4B._meta.pk.name, "parent")
366 ParkingLot4A.objects.create(
367 name="Parking4B",
368 address="21 Jump Street",
369 )
370
371 def test_all_fields_from_abstract_base_class(self):
372 """
373 Regression tests for #7588
374 """
375 # All fields from an ABC, including those inherited non-abstractly
376 # should be available on child classes (#7588). Creating this instance
377 # should work without error.
378 QualityControl.objects.create(
379 headline="Problems in Django",
380 pub_date=datetime.datetime.now(),
381 quality=10,
382 assignee="adrian",
383 )
384
385 def test_abstract_base_class_m2m_relation_inheritance(self):
386 # many-to-many relations defined on an abstract base class are
387 # correctly inherited (and created) on the child class.
388 p1 = Person.objects.create(name="Alice")
389 p2 = Person.objects.create(name="Bob")
390 p3 = Person.objects.create(name="Carol")
391 p4 = Person.objects.create(name="Dave")
392
393 birthday = BirthdayParty.objects.create(name="Birthday party for Alice")
394 birthday.attendees.set([p1, p3])
395
396 bachelor = BachelorParty.objects.create(name="Bachelor party for Bob")
397 bachelor.attendees.set([p2, p4])
398
399 parties = list(p1.birthdayparty_set.all())
400 self.assertEqual(parties, [birthday])
401
402 parties = list(p1.bachelorparty_set.all())
403 self.assertEqual(parties, [])
404
405 parties = list(p2.bachelorparty_set.all())
406 self.assertEqual(parties, [bachelor])
407
408 # A subclass of a subclass of an abstract model doesn't get its own
409 # accessor.
410 self.assertFalse(hasattr(p2, "messybachelorparty_set"))
411
412 # ... but it does inherit the m2m from its parent
413 messy = MessyBachelorParty.objects.create(name="Bachelor party for Dave")
414 messy.attendees.set([p4])
415 messy_parent = messy.bachelorparty_ptr
416
417 parties = list(p4.bachelorparty_set.all())
418 self.assertEqual(parties, [bachelor, messy_parent])
419
420 def test_abstract_verbose_name_plural_inheritance(self):
421 """
422 verbose_name_plural correctly inherited from ABC if inheritance chain
423 includes an abstract model.
424 """
425 # Regression test for #11369: verbose_name_plural should be inherited
426 # from an ABC even when there are one or more intermediate
427 # abstract models in the inheritance chain, for consistency with
428 # verbose_name.
429 self.assertEqual(InternalCertificationAudit._meta.verbose_name_plural, "Audits")
430
431 def test_inherited_nullable_exclude(self):
432 obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
433 self.assertQuerySetEqual(
434 SelfRefParent.objects.exclude(self_data=72), [obj.pk], attrgetter("pk")
435 )
436 self.assertQuerySetEqual(
437 SelfRefChild.objects.exclude(self_data=72), [obj.pk], attrgetter("pk")
438 )
439
440 def test_concrete_abstract_concrete_pk(self):
441 """
442 Primary key set correctly with concrete->abstract->concrete inheritance.
443 """
444 # Regression test for #13987: Primary key is incorrectly determined
445 # when more than one model has a concrete->abstract->concrete
446 # inheritance hierarchy.
447 self.assertEqual(
448 len(
449 [field for field in BusStation._meta.local_fields if field.primary_key]
450 ),
451 1,
452 )
453 self.assertEqual(
454 len(
455 [
456 field
457 for field in TrainStation._meta.local_fields
458 if field.primary_key
459 ]
460 ),
461 1,
462 )
463 self.assertIs(BusStation._meta.pk.model, BusStation)
464 self.assertIs(TrainStation._meta.pk.model, TrainStation)
465
466 def test_inherited_unique_field_with_form(self):
467 """
468 A model which has different primary key for the parent model passes
469 unique field checking correctly (#17615).
470 """
471
472 class ProfileForm(forms.ModelForm):
473 class Meta:
474 model = Profile
475 fields = "__all__"
476
477 User.objects.create(username="user_only")
478 p = Profile.objects.create(username="user_with_profile")
479 form = ProfileForm(
480 {"username": "user_with_profile", "extra": "hello"}, instance=p
481 )
482 self.assertTrue(form.is_valid())
483
484 def test_inheritance_joins(self):
485 # Test for #17502 - check that filtering through two levels of
486 # inheritance chain doesn't generate extra joins.
487 qs = ItalianRestaurant.objects.all()
488 self.assertEqual(str(qs.query).count("JOIN"), 2)
489 qs = ItalianRestaurant.objects.filter(name="foo")
490 self.assertEqual(str(qs.query).count("JOIN"), 2)
491
492 @expectedFailure
493 def test_inheritance_values_joins(self):
494 # It would be nice (but not too important) to skip the middle join in
495 # this case. Skipping is possible as nothing from the middle model is
496 # used in the qs and top contains direct pointer to the bottom model.
497 qs = ItalianRestaurant.objects.values_list("serves_gnocchi").filter(name="foo")
498 self.assertEqual(str(qs.query).count("JOIN"), 1)
499
500 def test_issue_21554(self):
501 senator = Senator.objects.create(name="John Doe", title="X", state="Y")
502 senator = Senator.objects.get(pk=senator.pk)
503 self.assertEqual(senator.name, "John Doe")
504 self.assertEqual(senator.title, "X")
505 self.assertEqual(senator.state, "Y")
506
507 def test_inheritance_resolve_columns(self):
508 Restaurant.objects.create(
509 name="Bobs Cafe",
510 address="Somewhere",
511 serves_pizza=True,
512 serves_hot_dogs=True,
513 )
514 p = Place.objects.select_related("restaurant")[0]
515 self.assertIsInstance(p.restaurant.serves_pizza, bool)
516
517 def test_inheritance_select_related(self):
518 # Regression test for #7246
519 r1 = Restaurant.objects.create(
520 name="Nobu", serves_hot_dogs=True, serves_pizza=False
521 )
522 r2 = Restaurant.objects.create(
523 name="Craft", serves_hot_dogs=False, serves_pizza=True
524 )
525 Supplier.objects.create(name="John", restaurant=r1)
526 Supplier.objects.create(name="Jane", restaurant=r2)
527
528 self.assertQuerySetEqual(
529 Supplier.objects.order_by("name").select_related(),
530 [
531 "Jane",
532 "John",
533 ],
534 attrgetter("name"),
535 )
536
537 jane = Supplier.objects.order_by("name").select_related("restaurant")[0]
538 self.assertEqual(jane.restaurant.name, "Craft")
539
540 def test_filter_with_parent_fk(self):
541 r = Restaurant.objects.create()
542 s = Supplier.objects.create(restaurant=r)
543 # The mismatch between Restaurant and Place is intentional (#28175).
544 self.assertSequenceEqual(
545 Supplier.objects.filter(restaurant__in=Place.objects.all()), [s]
546 )
547
548 def test_ptr_accessor_assigns_state(self):
549 r = Restaurant.objects.create()
550 self.assertIs(r.place_ptr._state.adding, False)
551 self.assertEqual(r.place_ptr._state.db, "default")
552
553 def test_related_filtering_query_efficiency_ticket_15844(self):
554 r = Restaurant.objects.create(
555 name="Guido's House of Pasta",
556 address="944 W. Fullerton",
557 serves_hot_dogs=True,
558 serves_pizza=False,
559 )
560 s = Supplier.objects.create(restaurant=r)
561 with self.assertNumQueries(1):
562 self.assertSequenceEqual(Supplier.objects.filter(restaurant=r), [s])
563 with self.assertNumQueries(1):
564 self.assertSequenceEqual(r.supplier_set.all(), [s])
565
566 def test_queries_on_parent_access(self):
567 italian_restaurant = ItalianRestaurant.objects.create(
568 name="Guido's House of Pasta",
569 address="944 W. Fullerton",
570 serves_hot_dogs=True,
571 serves_pizza=False,
572 serves_gnocchi=True,
573 )
574
575 # No queries are made when accessing the parent objects.
576 italian_restaurant = ItalianRestaurant.objects.get(pk=italian_restaurant.pk)
577 with self.assertNumQueries(0):
578 restaurant = italian_restaurant.restaurant_ptr
579 self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
580 self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
581
582 # One query is made when accessing the parent objects when the instance
583 # is deferred.
584 italian_restaurant = ItalianRestaurant.objects.only("serves_gnocchi").get(
585 pk=italian_restaurant.pk
586 )
587 with self.assertNumQueries(1):
588 restaurant = italian_restaurant.restaurant_ptr
589 self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
590 self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
591
592 # No queries are made when accessing the parent objects when the
593 # instance has deferred a field not present in the parent table.
594 italian_restaurant = ItalianRestaurant.objects.defer("serves_gnocchi").get(
595 pk=italian_restaurant.pk
596 )
597 with self.assertNumQueries(0):
598 restaurant = italian_restaurant.restaurant_ptr
599 self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
600 self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
601
602 def test_id_field_update_on_ancestor_change(self):
603 place1 = Place.objects.create(name="House of Pasta", address="944 Fullerton")
604 place2 = Place.objects.create(name="House of Pizza", address="954 Fullerton")
605 place3 = Place.objects.create(name="Burger house", address="964 Fullerton")
606 restaurant1 = Restaurant.objects.create(
607 place_ptr=place1,
608 serves_hot_dogs=True,
609 serves_pizza=False,
610 )
611 restaurant2 = Restaurant.objects.create(
612 place_ptr=place2,
613 serves_hot_dogs=True,
614 serves_pizza=False,
615 )
616
617 italian_restaurant = ItalianRestaurant.objects.create(
618 restaurant_ptr=restaurant1,
619 serves_gnocchi=True,
620 )
621 # Changing the parent of a restaurant changes the restaurant's ID & PK.
622 restaurant1.place_ptr = place3
623 self.assertEqual(restaurant1.pk, place3.pk)
624 self.assertEqual(restaurant1.id, place3.id)
625 self.assertEqual(restaurant1.pk, restaurant1.id)
626 restaurant1.place_ptr = None
627 self.assertIsNone(restaurant1.pk)
628 self.assertIsNone(restaurant1.id)
629 # Changing the parent of an italian restaurant changes the restaurant's
630 # ID & PK.
631 italian_restaurant.restaurant_ptr = restaurant2
632 self.assertEqual(italian_restaurant.pk, restaurant2.pk)
633 self.assertEqual(italian_restaurant.id, restaurant2.id)
634 self.assertEqual(italian_restaurant.pk, italian_restaurant.id)
635 italian_restaurant.restaurant_ptr = None
636 self.assertIsNone(italian_restaurant.pk)
637 self.assertIsNone(italian_restaurant.id)
638
639 def test_create_new_instance_with_pk_equals_none(self):
640 p1 = Profile.objects.create(username="john")
641 p2 = User.objects.get(pk=p1.user_ptr_id).profile
642 # Create a new profile by setting pk = None.
643 p2.pk = None
644 p2.user_ptr_id = None
645 p2.username = "bill"
646 p2.save()
647 self.assertEqual(Profile.objects.count(), 2)
648 self.assertEqual(User.objects.get(pk=p1.user_ptr_id).username, "john")
649
650 def test_create_new_instance_with_pk_equals_none_multi_inheritance(self):
651 c1 = Congressman.objects.create(state="PA", name="John", title="senator 1")
652 c2 = Person.objects.get(pk=c1.pk).congressman
653 # Create a new congressman by setting pk = None.
654 c2.pk = None
655 c2.id = None
656 c2.politician_ptr_id = None
657 c2.name = "Bill"
658 c2.title = "senator 2"
659 c2.save()
660 self.assertEqual(Congressman.objects.count(), 2)
661 self.assertEqual(Person.objects.get(pk=c1.pk).name, "John")
662 self.assertEqual(
663 Politician.objects.get(pk=c1.politician_ptr_id).title,
664 "senator 1",
665 )
666
667 def test_mti_update_parent_through_child(self):
668 Politician.objects.create()
669 Congressman.objects.create()
670 Congressman.objects.update(title="senator 1")
671 self.assertEqual(Congressman.objects.get().title, "senator 1")
672
673 def test_mti_update_grand_parent_through_child(self):
674 Politician.objects.create()
675 Senator.objects.create()
676 Senator.objects.update(title="senator 1")
677 self.assertEqual(Senator.objects.get().title, "senator 1")