Django ModelForm:save(commit=False) 用于什么? [英] Django ModelForm: What is save(commit=False) used for?

查看:28
本文介绍了Django ModelForm:save(commit=False) 用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我要使用 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?

换句话说,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 you 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆