Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django, property update a model instance

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?

like image 441
eugene Avatar asked Dec 19 '15 14:12

eugene


1 Answers

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 :

  1. Using 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().*
  2. 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.

like image 186
Dhia Avatar answered Sep 18 '22 23:09

Dhia