I'm having trouble understanding the difference between them, since I realized that I was using the .save () method to change my values, but I noticed that .update () exists.
I'm having trouble understanding the difference between them, since I realized that I was using the .save () method to change my values, but I noticed that .update () exists.
The save
method saves changes to a single object in the model (that is, a single DB line), whereas update
can change multiple objects at the same time. The differences are as follows:
objeto.save()
force_insert=True
argument to the save
method. It throws an exception if the object already exists, instead of making a UPDATE
. force_update=True
argument to the save
method. It throws an exception if the object does not exist, instead of doing a INSERT
. queryset.update()
SELECT
and then UPDATE
- it only does UPDATE
. Does not allow you to run your own logic before or after saving each individual object. In particular, it does not call the% method of% of each updated object;
If you need some custom logic during the save, do not use the save
method. Instead save in a loop:
for objeto in queryset:
objeto.save()
This is less efficient than the update
method (because it does N + 1 SQL commands instead of just 1), but may be necessary in some situations.
Updates all objects the queryset to a single, same value in a single SQL command. If the final value can be calculated from the current values of the records, you can use expressions F along with this command. Example:
MeuModelo.objects.filter(campo1=42).update(campo2 = F('campo2') + 1)
(Increments in 1 column update
of the entire line that has campo2
% equal to 42, all in a single SQL command)
There are several differences between the two.
TheUpdate
can be used to update multiple objects, Save
works to save a single row in the database.
In the case of multiple changes the Update
will give you much more performance, because it is a call by queryset.
In contrast to Save
is very easy to be written, as in the example below:
Class myModel(models.Model):
name = models.CharField()
date_created = models.DateField()
def save(self):
if not self.pk :
self.date_created = datetime.datetime.now()
super(myModel , self).save()
It's nothing wrong with using Save
, but if you have situations where you can make bulk changes, consider using Update
UPDATE
Save executes any overwriting, the Update will not execute overwriting of the save method of the model.
Here has a legal guide saying what exactly happens at the time of saving and also talks about how he knows whether it is an inclusion or change.