Skip to main content
 首页 » 编程设计

python之Django:在 clean() 方法中获取以前的值

2025年05月04日36txw1958

我有一个带有 IntegerField 的模型 CustomModel。

class CustomModel(models.Model): 
    count = models.IntegerField() 

当我在管理员中创建一个新的 CustomModel 实例时,我必须进行验证,所以我使用 clean 方法并可以访问值。

def clean(self): 
    value = self.count 
    ... 

我的问题:

当我更改 CustomModel 的实例时,我只能访问新的、更改后的值,而不能访问原始值。但是,为了进行验证,我必须比较新值和编辑实例之前的值。

我找不到如何获得访问权限的解决方案。有人知道吗?

请您参考如下方法:

为什么不利用 ModelForm ?表单数据保存分两步:

  1. 到表单实例
  2. 到模型实例

所以当你有一个表单时:

class YourForm(forms.ModelForm): 
 
    class Meta: 
        model = CustomModel 
        fields = ['count'] 
 
    def clean(self): 
        cleaned_data = super().clean() 
        count = cleaned_data.get('count') 
 
        if count < self.instance.count: 
            self.add_error('count', 'You cannot decrease the counter') 
 
        return cleanded_data 

然后您可以override the form在 django 管理站点中。