问题
I am unable to understand the reason why we use form.save(commit=False)
instead of simply using form.save
in Django-views
. Could someone explain me the difference and the necessities on both?
回答1:
form.save(commit=False)
is mostly used if you are working with ModelForm.
The main use case is if you have a ModelForm that doesn't contains all the required field of a model.
You need to save this form in the database, but because you didn't give it all the required fields you will get an error.
So the solution will be to save the form with commit=False and then you can manualy define the required values and then call the regular save.
The main diffrence is commit=False will not push the changes in the database, but it will create the all structure needed for it, but you will have to triger the regular save later on otherwise your form will not be saved in the database.
For exemple:
#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()
...
Another exemple is in the case you want to deal manually with many to many relationship.
The list of exemple are long but to be short, it's when you need to do intermediate step before saving a Model in the database.
来源:https://stackoverflow.com/questions/55822690/why-do-we-use-form-savecommit-false-in-django-views