2011-10-27 60 views
6

在这样的django自定义属性设置器中有什么办法吗?Django模型字段。自定义字段值设置器

class MyModel(models.Model): 
    myfield = models.CharField(length = 250) 

    @myfield.setter 
    def set_password(self, value): 
     self.password = encrypt(value) 
+1

本文由詹姆斯·贝内特给你上HOWTO一个好主意http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/ –

+0

related/dupe:http://stackoverflow.com/questions/2898711/django-model-fields-getter-setter#11108157 – Matt

回答

1

你真的会设置值上保存模型,所以最好重写save()方法(OT使用pre_save信号)。

+0

是的,我知道。但我只对属性感兴趣。 –

1

方法有什么问题?

instance.set_password('my_pw') 

您可以使用@property定义制定者: http://docs.python.org/library/functions.html#property

### Pasted from docs 

class C(object): 
    def __init__(self): 
     self._x = None 

    @property 
    def x(self): 
     """I'm the 'x' property.""" 
     return self._x 

    @x.setter 
    def x(self, value): 
     self._x = value 

    @x.deleter 
    def x(self): 
     del self._x 
+0

对不起,但它是关于纯类属性。不是关于Django模型。 –

+0

我想你可以有一个不同的属性。但真棒的想法。 +1!如果您找到解决方案,请告诉我。 –