Python Django:在clean()方法中获取上一个值
我有一个带有整数字段的模型Python Django:在clean()方法中获取上一个值,python,django,Python,Django,我有一个带有整数字段的模型CustomModel class CustomModel(models.Model): count = models.IntegerField() 当我在admin中创建一个新的CustomModel实例时,我必须进行验证,因此我使用clean方法,并可以使用访问值 def clean(self): value = self.count ... 我的问题是: 当我更改CustomModel的实例时,我只能访问新的、已更改的值,而不能访问原始
CustomModel
class CustomModel(models.Model):
count = models.IntegerField()
当我在admin中创建一个新的CustomModel
实例时,我必须进行验证,因此我使用clean
方法,并可以使用访问值
def clean(self):
value = self.count
...
我的问题是:
当我更改CustomModel的实例时,我只能访问新的、已更改的值,而不能访问原始值。但是,为了进行验证,我必须将新值与编辑实例之前的值进行比较
我找不到如何访问的解决方案。有人知道吗?为什么不利用这个机会呢?表单数据分两步保存:
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
class YourForm(forms.ModelForm):
类元:
模型=自定义模型
字段=['count']
def清洁(自清洁):
cleaned_data=super().clean()
计数=已清理的数据。获取('count')
如果计数
然后,您可以在django管理站点中找到解决方案。也可以使用该模型:
def clean(self):
if self.pk:
previous_count = self.__class__.objects.get(pk=self.pk).count
else:
previous_count = None # If saving a new instance
self.\uuuu class\uuuuu
访问模型类并获取当前存储的.count
值。此clean
方法在哪里?如果它在表单上,您可以查看self.instance.count
。否,clean
方法在my models.py中(它是CustomModel的一种方法)。