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