|
Revision 5876, 1.0 kB
(checked in by mtredinnick, 2 years ago)
|
Fixed #5111 -- Set svn:eol-style to 'native' on files that didn't have it
already.
|
- Property svn:eol-style set to
native
|
| Line | |
|---|
| 1 |
""" |
|---|
| 2 |
22. Using properties on models |
|---|
| 3 |
|
|---|
| 4 |
Use properties on models just like on any other Python object. |
|---|
| 5 |
""" |
|---|
| 6 |
|
|---|
| 7 |
from django.db import models |
|---|
| 8 |
|
|---|
| 9 |
class Person(models.Model): |
|---|
| 10 |
first_name = models.CharField(max_length=30) |
|---|
| 11 |
last_name = models.CharField(max_length=30) |
|---|
| 12 |
|
|---|
| 13 |
def _get_full_name(self): |
|---|
| 14 |
return "%s %s" % (self.first_name, self.last_name) |
|---|
| 15 |
|
|---|
| 16 |
def _set_full_name(self, combined_name): |
|---|
| 17 |
self.first_name, self.last_name = combined_name.split(' ', 1) |
|---|
| 18 |
|
|---|
| 19 |
full_name = property(_get_full_name) |
|---|
| 20 |
|
|---|
| 21 |
full_name_2 = property(_get_full_name, _set_full_name) |
|---|
| 22 |
|
|---|
| 23 |
__test__ = {'API_TESTS':""" |
|---|
| 24 |
>>> a = Person(first_name='John', last_name='Lennon') |
|---|
| 25 |
>>> a.save() |
|---|
| 26 |
>>> a.full_name |
|---|
| 27 |
'John Lennon' |
|---|
| 28 |
|
|---|
| 29 |
# The "full_name" property hasn't provided a "set" method. |
|---|
| 30 |
>>> a.full_name = 'Paul McCartney' |
|---|
| 31 |
Traceback (most recent call last): |
|---|
| 32 |
... |
|---|
| 33 |
AttributeError: can't set attribute |
|---|
| 34 |
|
|---|
| 35 |
# But "full_name_2" has, and it can be used to initialise the class. |
|---|
| 36 |
>>> a2 = Person(full_name_2 = 'Paul McCartney') |
|---|
| 37 |
>>> a2.save() |
|---|
| 38 |
>>> a2.first_name |
|---|
| 39 |
'Paul' |
|---|
| 40 |
"""} |
|---|