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