djangodjango-models

Are consecutive django model save calls safe?


I'm having trouble with a field that seems to sometimes not update. Just want to know if the following is unsafe on a Django model instance.

obj.field1 = True
obj.save()
obj.field2 = True
obj.save()

Since I'm not calling obj.update_from_db() is there any risk the second save resets/overrides field1 ?

There are no post_save hooks involved, the surrounding code is synchronous and the DB backend is PostgreSQL.

Also, is save() synchronous (in the sense that the DB update will happen before the function returns)?


Solution

  • .save() is generally speaking strictly synchronous. Which is to say that when you call .save(), the commit will succeed before the method returns (or it will fail and the method will throw an exception).

    There are a few situations where you this won't necessarily be the case (but they're more towards the advanced side of use-cases):