• Home
  • Django
  • Trigger post_save after transaction is committed

Trigger post_save after transaction is committed

linkaiyi
Follow

Triger post_save after transaction is committed

use transaction on committed

from django.db import transaction
from django.db.models.signals import post_save

@receiver(post_save, sender=Photo)
def save_photo(**kwargs):
    transaction.on_commit(lambda: talk_to_elasticsearch(kwargs['instance']))

There are 2 approaches here:

  1. you are going to inspect the instance in the post_save method and decide that the model was saved successfully or not; simplest way to do that: in the save method, after the transaction executed successfully, annotate your instance with a flag, say instance.saved_successfully = True, which you will test in the post_save handler.
  2. you are going to ditch the post_save signal and create a custom signal for yourself, which you will trigger after the transaction ran successfully.
Object has 0 attachments

Was this article helpful?

This article is viewed 10 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support