After obtaining data from a model form based on a Model, say
form_data = MyModelForm(request.POST)
Then I can either create an instance of Model by
instance = Model(**form_data.cleaned_data)
Or by
instance = form_data.save()
I wonder which one is the preferred way in the django world
There is a significant difference between the two.
instance = Model(**form_data.cleaned_data)
doesn't save the object in the database. It only creates a local instance.
instance = form_data.save()
adds the object to the database (it performs a commit, if so supported), and it also has the side effect of triggering validation.
If you want to do custom post-processing of the object before saving it, you pass commit=False
to the save()
method.
instance = form_data.save(commit=False)
# do some stuff with instance
instance.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With