且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django模型字段。自定义字段值设置器

更新时间:2023-02-01 22:41:42

方法有什么问题?

  instance.set_password('my_pw')

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

  ###从文档中粘贴

class C(object):
def __init __(self):
self._x =无

@property
def x(self):
我是'x'属性。
return self._x

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

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


Is there any way to do in django custom property setter like this?

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

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

What's wrong with a method?

instance.set_password('my_pw')

You can use @property to define setters: 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