Django

Code

Changeset 6346

Show
Ignore:
Timestamp:
09/15/07 20:57:25 (10 months ago)
Author:
mtredinnick
Message:

Fixed #3703 -- Added pk property to models. Thanks, Collin Grady and jeromie@gmail.com.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/base.py

    r6269 r6346  
    8383    def _get_pk_val(self): 
    8484        return getattr(self, self._meta.pk.attname) 
     85 
     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) 
    8590 
    8691    def __repr__(self): 
  • django/trunk/docs/model-api.txt

    r6304 r6346  
    12841284 
    12851285Each model requires exactly one field to have ``primary_key=True``. 
     1286 
     1287The ``pk`` property 
     1288------------------- 
     1289**New in Django development version** 
     1290 
     1291Regardless of whether you define a primary key field yourself, or let Django 
     1292supply one for you, each model will have a property called ``pk``. It behaves 
     1293like a normal attribute on the model, but is actually an alias for whichever 
     1294attribute is the primary key field for the model. You can read and set this 
     1295value, just as you would for any other attribute, and it will update the 
     1296correct field in the model. 
    12861297 
    12871298Admin options 
  • django/trunk/tests/modeltests/basic/models.py

    r5876 r6346  
    3232# Now it has an ID. Note it's a long integer, as designated by the trailing "L". 
    3333>>> a.id 
     341L 
     35 
     36# Models have a pk property that is an alias for the primary key attribute (by 
     37# default, the 'id' attribute). 
     38>>> a.pk 
    34391L 
    3540 
  • django/trunk/tests/modeltests/custom_pk/models.py

    r6200 r6346  
    5757[<Employee: Fran Bones>, <Employee: Dan Jones>] 
    5858 
     59# The primary key can be accessed via the pk property on the model. 
     60>>> e = Employee.objects.get(pk='ABC123') 
     61>>> e.pk 
     62u'ABC123' 
     63 
     64# Or we can use the real attribute name for the primary key: 
     65>>> e.employee_code 
     66u'ABC123' 
     67 
    5968# Fran got married and changed her last name. 
    6069>>> fran = Employee.objects.get(pk='XYZ456')