Django ModelForm:什么是save(commit = False)用于? [英] Django ModelForm: What is save(commit=False) used for?
问题描述
为什么要使用 save(commit = False)
,而不是从 ModelForm
中创建一个表单对象子类并运行 is_valid()
以验证表单和模型?
Why would I ever use save(commit=False)
instead of just creating a form object from the ModelForm
subclass and running is_valid()
to validate both the form and model?
换句话说,什么是code> save(commit = False)?
In other words, what is save(commit=False)
for?
如果你不介意,你能提供假设的情况,有用吗?
If you don't mind, could you guys provide hypothetical situations where this might be useful?
提前感谢
推荐答案
您可以从表单获取大部分模型数据,但需要使用非表单数据填充一些 null = False
字段。
That's useful when you get most of your model data from a form, but need to populate some null=False
fields with non-form data.
使用commit = False保存一个模型对象,然后可以添加额外的数据并保存。
Saving with commit=False gets you a model object, then you can add your extra data and save it.
这篇关于Django ModelForm:什么是save(commit = False)用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!