Ticket #14163: inheritance_pk.diff

File inheritance_pk.diff, 2.1 KB (added by Anssi Kääriäinen, 14 years ago)

Made sure to test pk property directly

  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index 1927b1e..0ac34e4 100644
    a b class Model(object):  
    399399        return getattr(self, meta.pk.attname)
    400400
    401401    def _set_pk_val(self, value):
    402         return setattr(self, self._meta.pk.attname, value)
     402        ret = setattr(self, self._meta.pk.attname, value)
     403        parent_link = self._meta.pk
     404        while (isinstance(parent_link, OneToOneField) and parent_link.rel.parent_link):
     405            parent_link = parent_link.rel.get_related_field()
     406            setattr(self, parent_link.attname, value)
     407        return ret
    403408
    404409    pk = property(_get_pk_val, _set_pk_val)
    405410
  • tests/modeltests/model_inheritance/models.py

    diff --git a/tests/modeltests/model_inheritance/models.py b/tests/modeltests/model_inheritance/models.py
    index 95bf5ab..5a6d7c2 100644
    a b class ParkingLot(Place):  
    119119    def __unicode__(self):
    120120        return u"%s the parking lot" % self.name
    121121
     122class CarInLot(models.Model):
     123    parking_lot = models.ForeignKey(ParkingLot)
     124
    122125#
    123126# Abstract base classes with related models where the sub-class has the
    124127# same name in a different app and inherits from the same abstract base
    DoesNotExist: Restaurant matching query does not exist.  
    345348>>> Restaurant.objects.get(lot__name='Well Lit')
    346349<Restaurant: Ristorante Miron the restaurant>
    347350
     351# Setting the pk of a model with OneToOneField, where parent_link=True, will
     352# also set the parent model's pk.
     353
     354>>> ir2 = ItalianRestaurant(pk=1)
     355>>> ir2.id == ir2.pk
     356True
     357>>> ir2.pk = 2
     358>>> ir2.pk == ir2.id
     359True
     360
     361>>> park3 = ParkingLot(pk=1)
     362>>> park3.pk == park3.id
     363True
     364>>> park3.parent_id == park3.pk
     365True
     366>>> cil = CarInLot(parking_lot=park3)
     367>>> cil.parking_lot_id == 1
     368True
     369
    348370# The update() command can update fields in parent and child classes at once
    349371# (although it executed multiple SQL queries to do so).
    350372>>> Restaurant.objects.filter(serves_hot_dogs=True, name__contains='D').update(name='Demon Puppies', serves_hot_dogs=False)
Back to Top