When should the save method be called in Django?

If the save method is called after each create method or calls the create method, which automatically calls the save method?

If the save method is called automatically after creating the object, then what would be a good use case for the save method?

Thanks.

+6
source share
3 answers

No save() needs to be called after create() .

from docs to create:

Convenient method for creating an object and saving it in just one step

it should be used instead of creating the object in the usual way, and then saved using object.save ()

+8
source

The save method should be used when you modify an object that you received with other means than create , for example .objects.get . Otherwise, your changes will be lost.

+2
source

Here is an example snippet that shows a good use for the save method. It basically takes data from the submitted form, and then adds additional information behind the scenes.

 #Model class Foo(models.Model): field_one = models.CharField(max_length=10) field_two = models.CharField(max_length=10) field_three = models.CharField(max_length=10) #Form class FooForm(ModelForm): class Meta: model = Foo exclude = ('field_three') #form will just show field_one and field_two #View def FooView(request): if request.method == 'POST' form = FooForm(request.POST) #gets field_one and two from form data if form.is_valid(): new_foo = form.save(commit = False) #doesn't actually save yet new_foo.field_three = 'Foobar!' #add data to field_three new_foo.save() #now it saves all 3 fields else: form = FooForm() return #add some sort of http response here 

Here's the Django Docs with more info on save () and commit = False

As an aside - I just realized that if you add a static line to the model, for example, using my example, you are doing it wrong. But the idea is haha.

+1
source

Source: https://habr.com/ru/post/891716/


All Articles