我无法理解为什么使用form.save(commit=False)
而不是简单地使用form.save
in的原因Django-views
。有人可以解释一下两者的区别和必要性吗?
form.save(commit=False)
如果您正在使用ModelForm,则通常使用它。主要用例是,如果您的ModelForm不包含模型的所有必填字段。
您需要将此表单保存在数据库中,但是由于未将所有必填字段都提供给它,因此会出现错误。
因此,解决方案是使用commit = False保存表单,然后您可以手动定义所需的值,然后调用常规保存。
主要区别是commit = False不会将更改推送到数据库中,但是会创建它所需的所有结构,但是稍后您将不得不触发常规保存,否则您的表单将不会保存在数据库中。
举个例子:
#create a Dog class with all fields as mandatory
class Dog(models.Model):
name = models.CharField(max_length=50)
race = models.CharField(max_length=50)
age = models.PositiveIntegerField()
#create a modelForm with only name and age
class DogForm(forms.ModelForm):
class Meta:
model = Dog
fields = ['name', 'age']
#in your view use this form
def dog_view(request):
...
form = DogForm(request.POST or None)
#if the form is valid we need to add a race otherwise we will get an error
if form.is_valid():
dog = form.save(commit=False)
#define the race here
dog.race = 'Labrador retriever'
#and then do the regular save to push the change in the database
dog.save()
...
另一个例子是您要手动处理多对多关系。
示例列表很长,但总之很短,这是在您需要在数据库中保存模型之前执行中间步骤的时候。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句