Django - 如果表单数据是新的或者是否正在更改旧数据,如何在clean方法中知道

Hel*_*org 12 django django-forms

如何在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
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 27

检查self.cleaned_data['some_field']打击self.instance.some_field.

检查对象是否是新对象的快速方法是查看是否self.instance.pk有值.None除非对象已存在,否则它将被删除.


Ala*_*air 5

在 中,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
Run Code Online (Sandbox Code Playgroud)