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
- ForeignKey dropdown selector by rubic 6 years, 2 months ago
- Gravatar support for Django comments by jonathan 4 years, 7 months ago
- Another JsonResponse by kcarnold 4 years, 11 months ago
- Replace model select widget in admin with a readonly link to the related object by ekellner 4 years, 8 months ago
- SuperChoices by willhardy 4 years, 6 months ago
Comments
I've been meaning to submit a patch to add a property on the built-in
Usermodel for getting/setting the full name (there's aget_full_namemethod 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 :)#