Ticket #3703: pk_property_with_tests.diff

File pk_property_with_tests.diff, 1.6 KB (added by jeromie@…, 17 years ago)

Patch including tests and documentation

  • django/db/models/base.py

     
    8383    def _get_pk_val(self):
    8484        return getattr(self, self._meta.pk.attname)
    8585
     86    def _set_pk_val(self, value):
     87        return setattr(self, self._meta.pk.attname, value)
     88
     89    pk = property(_get_pk_val, _set_pk_val)
     90
    8691    def __repr__(self):
    8792        return smart_str(u'<%s: %s>' % (self.__class__.__name__, unicode(self)))
    8893
  • tests/modeltests/basic/models.py

     
    3333>>> a.id
    34341L
    3535
     36# New in Django development version:
     37# Models have a pk attribute that points to the primary key
     38# By default this is the id
     39>>> a.pk
     401L
     41
    3642# Access database columns via Python attributes.
    3743>>> a.headline
    3844'Area man programs in Python'
  • tests/modeltests/custom_pk/models.py

     
    5656>>> Employee.objects.filter(pk__in=['ABC123','XYZ456'])
    5757[<Employee: Fran Bones>, <Employee: Dan Jones>]
    5858
     59# New in Django development version:
     60# pk can be accessed like any other attribute
     61>>> e = Employee.objects.get(pk='ABC123')
     62>>> e.pk
     63u'ABC123'
     64
    5965# Fran got married and changed her last name.
    6066>>> fran = Employee.objects.get(pk='XYZ456')
    6167>>> fran.last_name = 'Jones'
Back to Top