diff options
Diffstat (limited to 'parts/django/tests/modeltests/properties')
-rw-r--r-- | parts/django/tests/modeltests/properties/__init__.py | 0 | ||||
-rw-r--r-- | parts/django/tests/modeltests/properties/models.py | 21 | ||||
-rw-r--r-- | parts/django/tests/modeltests/properties/tests.py | 20 |
3 files changed, 41 insertions, 0 deletions
diff --git a/parts/django/tests/modeltests/properties/__init__.py b/parts/django/tests/modeltests/properties/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/parts/django/tests/modeltests/properties/__init__.py diff --git a/parts/django/tests/modeltests/properties/models.py b/parts/django/tests/modeltests/properties/models.py new file mode 100644 index 0000000..390efe3 --- /dev/null +++ b/parts/django/tests/modeltests/properties/models.py @@ -0,0 +1,21 @@ +""" +22. Using properties on models + +Use properties on models just like on any other Python object. +""" + +from django.db import models + +class Person(models.Model): + first_name = models.CharField(max_length=30) + last_name = models.CharField(max_length=30) + + def _get_full_name(self): + return "%s %s" % (self.first_name, self.last_name) + + def _set_full_name(self, combined_name): + self.first_name, self.last_name = combined_name.split(' ', 1) + + full_name = property(_get_full_name) + + full_name_2 = property(_get_full_name, _set_full_name) diff --git a/parts/django/tests/modeltests/properties/tests.py b/parts/django/tests/modeltests/properties/tests.py new file mode 100644 index 0000000..e31ac58 --- /dev/null +++ b/parts/django/tests/modeltests/properties/tests.py @@ -0,0 +1,20 @@ +from django.test import TestCase +from models import Person + +class PropertyTests(TestCase): + + def setUp(self): + self.a = Person(first_name='John', last_name='Lennon') + self.a.save() + + def test_getter(self): + self.assertEqual(self.a.full_name, 'John Lennon') + + def test_setter(self): + # The "full_name" property hasn't provided a "set" method. + self.assertRaises(AttributeError, setattr, self.a, 'full_name', 'Paul McCartney') + + # But "full_name_2" has, and it can be used to initialise the class. + a2 = Person(full_name_2 = 'Paul McCartney') + a2.save() + self.assertEqual(a2.first_name, 'Paul') |