假设我有一个模型文章及其ModelForm ArticleForm。
>>> a_form = ArticleForm({"headline" : "My headline"})
>>> b = Article()
>>> b.save()
现在我想将a_form绑定到b实例并保存它(即用a_form字段更新b对象)。有没有办法做到这一点?
类似的东西:
>>> a_form.assign_instance(b) # WOULD LIKE TO HAVE SOMETHING LIKE THAT
>>> a_form.save()
注意:我知道我可以打电话
>>> a_form = ArticleForm({"headline" : "My headline"}, instance=b)
>>> a_form.save()
......但这不是这里的意图。我需要知道在保存之前是否可以将实例隐藏到模型中。感谢。
答案 0 :(得分:1)
你可以这样做:
a_form.instance = b
a_form.save()
但Django在表单保存之前修改实例的方法是覆盖表单save()
方法。你可以这样做:
class ArticleForm(forms.ModelForm):
...
def save(self):
instance = self.instance # Do with instance what every you want
super(ArticleForm, self).save()