Is the post_save call happening inside a transactional operation?
sobes.tech AI
Answer from AI
In Django, the post_save signal is called immediately after a model instance is saved, but not necessarily within a transactional operation.
If the save occurs within an explicit transaction (for example, using transaction.atomic()), then post_save triggers at the moment of saving, but the transaction may not yet be committed. This means that post_save handlers can see changes before the transaction is committed.
If it is important for the code to run after a successful commit of the transaction, you should use the transaction.on_commit() signal, which allows you to register a function that is called exactly after the transaction is committed.
Example:
from django.db import transaction
@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, **kwargs):
transaction.on_commit(lambda: do_something(instance))
Thus, post_save is called upon saving, but it does not guarantee that the transaction has already been completed.