Login

Using Python properties in models

Author:
rubic
Posted:
March 5, 2007
Language:
Python
Version:
Pre .96
Tags:
property model
Score:
3 (after 3 ratings)

After reading the comment to my snippet #49 it occurs to me that Python properties may not be obvious to everyone, and may be underutilized in Django models.

Here is a simple example demonstrating a property to format a Person's name.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django.db import models

class Person(models.Model):
    """Demonstrate model attribute with a Python property
    >>> p = Person(firstName='Jeff', lastName='Bauer')
    >>> p.name
    'Bauer, Jeff'
    >>>
    """
    firstName = models.CharField(maxlength=20)
    lastName = models.CharField(maxlength=20)
    middleName = models.CharField(maxlength=20, blank=True)

    def _name(self):
        if self.middleName:
            return "%s, %s %s." % (self.lastName,
                                   self.firstName,
                                   self.middleName[:1])
        else:
            return "%s, %s" % (self.lastName, self.firstName)
    name = property(_name)

More like this

  1. Cached model property decorator (like @property) by homunq 3 years, 3 months ago
  2. Application-independent permalink to admin url for an object by dchandek 7 years ago
  3. Property Attributes in Memcache by ori 3 years, 4 months ago
  4. RFC: Shim to allow view classes rather than functions by peterbraden 5 years, 12 months ago
  5. base64 encoding/decoding property for storing binary data in Django TextFields. by bikeshedder 5 years, 8 months ago

Comments

ubernostrum (on March 5, 2007):

I've been meaning to submit a patch to add a property on the built-in User model for getting/setting the full name (there's a get_full_name method on it right now, and IIRC it's not a property because pre-magic-removal Django had issues with properties on model classes); it'd be nice to have an example of that in Django itself to point to :)

#

Please login first before commenting.