equal
deleted
inserted
replaced
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(maxlength=30) |
|
11 last_name = models.CharField(maxlength=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 """} |
|