Ticket #3148: 3148.5.diff
File 3148.5.diff, 3.4 KB (added by , 16 years ago) |
---|
-
django/db/models/fields/__init__.py
77 77 editable=True, serialize=True, unique_for_date=None, 78 78 unique_for_month=None, unique_for_year=None, validator_list=None, 79 79 choices=None, help_text='', db_column=None, db_tablespace=None, 80 auto_created=False ):80 auto_created=False, use_property=None): 81 81 self.name = name 82 82 self.verbose_name = verbose_name 83 83 self.primary_key = primary_key 84 84 self.max_length, self._unique = max_length, unique 85 85 self.blank, self.null = blank, null 86 self.model_property = use_property 86 87 # Oracle treats the empty string ('') as null, so coerce the null 87 88 # option whenever '' is a possible value. 88 89 if self.empty_strings_allowed and connection.features.interprets_empty_strings_as_nulls: … … 171 172 cls._meta.add_field(self) 172 173 if self.choices: 173 174 setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) 175 if self.model_property: 176 if len(self.model_property) < 2: 177 raise ValueError("You must specify at least a getter and a setter method") 178 # Create a property on ``cls`` with the methods given. 179 setattr(cls, '%s' % self.name, 180 property(*self.model_property)) 174 181 175 182 def get_attname(self): 176 183 return self.name -
tests/modeltests/properties/models.py
20 20 21 21 full_name_2 = property(_get_full_name, _set_full_name) 22 22 23 class PropModel(models.Model): 24 def _set_name(self, value): 25 self.__name = value 26 27 def _get_name(self): 28 return self.__name 29 30 name = models.CharField(max_length=30, use_property=(_get_name, _set_name)) 31 23 32 __test__ = {'API_TESTS':""" 24 33 >>> a = Person(first_name='John', last_name='Lennon') 25 34 >>> a.save() … … 37 46 >>> a2.save() 38 47 >>> a2.first_name 39 48 'Paul' 49 50 # Now the field properties 51 >>> b = PropModel(name='John') 52 >>> b.save() 53 >>> b.name 54 'John' 55 >>> b._get_name() 56 'John' 57 >>> b.name = 'Smith' 58 >>> b._get_name() 59 'Smith' 40 60 """} 61 -
docs/model-api.txt
738 738 739 739 Like ``unique_for_date`` and ``unique_for_month``. 740 740 741 ``use_property`` 742 ~~~~~~~~~~~~~~~~ 743 744 It is possible to create a property around a field. It is specially usefull if 745 you want to control when the value for a field gets changed or accessed. 746 747 The ``use_property`` option takes a tuple of the parameters that will be passed to 748 ``property()`` to construct it. 749 750 But note that at least getter and setter functions must be given. 751 752 Example:: 753 754 from django.db import models 755 756 class Person(models.Model): 757 def _get_name(self): 758 return self.__name 759 def _set_name(self, value): 760 self.__name = value 761 762 name = models.CharField(max_length=30, use_property=(_get_name, _set_name)) 763 741 764 ``validator_list`` 742 765 ~~~~~~~~~~~~~~~~~~ 743 766