2011-10-27 117 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!如果您找到解決方案,請告訴我。 –