我如何在MyForm.clean()中知道数据是新的,还是已经保存的数据正在被修改?
is_this_new_data()在下面的代码中应该是什么样的?
class MyForm(forms.ModelForm):
def clean(self):
cleaned_data = self.cleaned_data
if is_this_new_data(self):
# perform some checks if this is new data
else:
# do nothing if this is data being modifed
return cleaned_data
答案 0 :(得分:25)
针对self.cleaned_data['some_field']
检查self.instance.some_field
。
检查对象是否为新对象的快速方法是查看self.instance.pk
是否有值。除非对象已存在,否则它将为None
。
答案 1 :(得分:3)
在clean
中,您可以访问changed_data
属性,该属性是已更改字段名称的列表。
def clean(self):
cleaned_data = self.cleaned_data:
for field_name in self.changed_data:
# loop through the fields which have changed
print "field %s has changed. new value %s" % (field_name, cleaned_data[field_name])
do_something()
return cleaned_data