如果模型表单正在创建新记录或更新现有记录,有没有办法在表单 .save() 方法中找到?

Is there a way to find in forms .save() method if Model Form is creating a new record or updating existing one?

我要知道表单是在创建新记录还是在更新现有记录,我正在做的是

class MyForm(forms.ModelForm):
    def save(self, commit=True):
        _new = True if not self.instance.id else False
        keyword = super(MyForm, self).save()
        if _new:
            do_something()
        return keyword

在调用 super(MyForm, self).save() 之后是否有其他方法可以找到它,而无需在调用 "super" 之前明确检查它,就像我对“_new”所做的那样?

它只是 .id(实际上是 .pk)字段。如果它是 None(可能是任何 'falsy' 值),那么它就是一个新记录并且 .save() 将使用 INSERT。否则它是现有记录的键,它将使用 UPDATE.

https://docs.djangoproject.com/en/1.8/ref/models/instances/#how-django-knows-to-update-vs-insert

不,没有其他办法。 ModelForm 没有指示对象已创建或更新的字段。事实上,您可以将未保存的模型作为 instance 传递给 ModelForm,在这种情况下,表单根本不会构造对象:

form = MyForm(instance=MyModel())

因此检查 self.instance.pk 是完成此任务的唯一方法。