Ticket #3148: django-modelfield-getter-setters.diff
File django-modelfield-getter-setters.diff, 3.5 KB (added by , 15 years ago) |
---|
-
django/db/models/base.py
208 208 else: 209 209 setattr(cls, name, value) 210 210 211 # Add properties assigned via getter, setter and deleter field 212 # decorators 213 if hasattr(value, '_property') and value._property: 214 setattr(cls, name, property(**value._property)) 215 del(value._property) 216 211 217 def _prepare(cls): 212 218 """ 213 219 Creates some methods once self._meta has been populated. -
django/db/models/fields/__init__.py
97 97 self.creation_counter = Field.creation_counter 98 98 Field.creation_counter += 1 99 99 100 self._property = {} # stores kwargs for property ('fget', 'fset', 'fdel') 101 100 102 def __cmp__(self, other): 101 103 # This is needed because bisect does not take a comparison function. 102 104 return cmp(self.creation_counter, other.creation_counter) … … 148 150 return self._unique or self.primary_key 149 151 unique = property(unique) 150 152 153 def setter(self, f): 154 self._property['fset'] = f 155 156 def getter(self, f): 157 self._property['fget'] = f 158 159 def deleter(self, f): 160 self._property['fdel'] = f 161 151 162 def set_attributes_from_name(self, name): 152 163 self.name = name 153 164 self.attname, self.column = self.get_attname_column() -
tests/regressiontests/model_fields/tests.py
7 7 from django.core.exceptions import ValidationError 8 8 9 9 from models import Foo, Bar, Whiz, BigD, BigS, Image 10 from models import FooGetSet 10 11 11 12 try: 12 13 from decimal import Decimal … … 144 145 bs = BigS.objects.create(s = 'slug'*50) 145 146 bs = BigS.objects.get(pk=bs.pk) 146 147 self.assertEqual(bs.s, 'slug'*50) 148 149 class FieldProperties(django.test.TestCase): 150 def test_get_set(self): 151 """ 152 Test basic getter and setter functionality of a SlugField 153 """ 154 f = FooGetSet( s = "test" ) 155 self.assertEqual(f.s, "test") 156 f.s = "test2" 157 self.assertEqual(f.s, "test2") 158 159 def set_non_acceptable(): 160 f.s = "not_acceptable" 161 self.assertRaises(ValueError, set_non_acceptable) 162 self.assertEqual(f.s, "test2") 163 164 f.save() 165 f = FooGetSet.objects.get(pk=f.pk) 166 self.assertEqual(f.s, "test2") 167 -
tests/regressiontests/model_fields/models.py
51 51 class BigS(models.Model): 52 52 s = models.SlugField(max_length=255) 53 53 54 class FooGetSet(models.Model): 55 s = models.SlugField(max_length=255) 54 56 57 @s.getter 58 def get_s(self): 59 return self._s 60 @s.setter 61 def set_s(self, value): 62 if value is "not_acceptable": 63 raise ValueError("not acceptable") 64 self._s = value 65 55 66 ############################################################################### 56 67 # ImageField 57 68