Trigering post_save signal only after transaction has completed

前端 未结 3 731
旧巷少年郎
旧巷少年郎 2020-12-30 02:27

I have written some APIs, for which the respective functions executive inside a transaction block. I am calling the save() method (after some modifications) on

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 03:18

    I think the simplest way is to use transaction.on_commit(). Here's an example using the models.Model subclass Photo that will only talk to Elasticsearch once the current transaction is over:

    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']))
    

    Note that if the transaction.on_commit() gets executed while not in an active transaction, it will run right away.

提交回复
热议问题