1. instance.save()
2. instance.foo = foo; instance.save(update_fields=['foo'])
3. InstanceClass.objects.filter(id=instance.id).update(foo=foo)
I found that #3 is sometimes not reliable.
after I run #3, occasionally foo is not properly set (not commited?)
I used to use #3 when I don't want to run signal handlers.
When to use each of the above 3?
If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update()
, rather than loading the model object into memory. For example, instead of doing this:
instance = Entry.objects.get(id=10)
instance.comments_on = False
instance.save()
do this:
Entry.objects.filter(id=10).update(comments_on=False)
NB :
update()
also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().
*update()
does an update at the SQL level and, thus, does not call any save()
, so if you have an overrided save() method you have to use the first way with get()
and save()
.Check the Queryset documentation, it's all explained here.
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