2
I’m having trouble understanding the difference between them, because I realized I was using the method. save() to change my values, but I noticed that there is . update().
2
I’m having trouble understanding the difference between them, because I realized I was using the method. save() to change my values, but I noticed that there is . update().
2
There are several differences between the two.
The Update
can be used to update various objects, the Save
works to save a single line in the bank.
In the case of multiple Update
will give you much more performasse, because it is a call by queryset.
Against the background of Save
is very easy to be on writing, 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()
There’s nothing wrong with wearing the Save
, but if you have situations where you can make mass changes think about using the Update
UPDATING
Save performs any over writing, Update will not run the over writing of the model’s Save method.
Here has a legal guide telling what happens exactly at the time of saving and also talks about how he knows if it is an inclusion or change.
2
The method save
saves changes to a single model object (i.e., a single BD line), while the update
can change multiple objects at the same time. The differences are as follows:
objeto.save()
force_insert=True
to the method save
. He will make an exception if the object already exists, instead of making a UPDATE
.force_update=True
to the method save
. He will make an exception if the object does not exist instead of making a INSERT
.queryset.update()
SELECT
and then a UPDATE
- he just does the UPDATE
.It does not allow to execute logic of its own before or after saving each individual object. In particular, it flame the method save
of each updated object;
If you need some custom logic while saving, don’t use the method update
. Instead save in a loop:
for objeto in queryset:
objeto.save()
This is less efficient than the method update
(because it makes N+1 SQL commands instead of just 1), but may be necessary in some situations.
Updates all the objects of queryset for a single, same value, in a single SQL command. If the final value can be calculated from the current values of the records, one can use expressions F along with this command. Example:
MeuModelo.objects.filter(campo1=42).update(campo2 = F('campo2') + 1)
(Increment by 1 column campo2
of every line that has campo1
equal to 42, all this in a single SQL command)
Excellent response!
Browser other questions tagged django
You are not signed in. Login or sign up in order to post.
+1 Note that these signs
pre_save
andpost_save
are not sent in the case ofupdate
, only ofsave
.– mgibsonbr