我不能理解为什么我们在Django-views中使用form.save(commit=False)而不是简单地使用form.save。有人能给我解释一下两者的区别和必要性吗?
发布于 2019-04-24 15:52:14
如果您使用的是ModelForm,则通常使用form.save(commit=False)。主要的用例是,如果您的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()
...另一个例子是你想手动处理多对多关系的情况。
示例列表很长,但长话短说,它是在将模型保存到数据库之前需要执行中间步骤的时候。
https://stackoverflow.com/questions/55822690
复制相似问题