Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: create object from constructor or model form

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

like image 957
airfang Avatar asked Mar 28 '12 03:03

airfang


1 Answers

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()
like image 153
Burhan Khalid Avatar answered Oct 01 '22 19:10

Burhan Khalid