django TransactionManagementError when using signals

后端 未结 1 1689
陌清茗
陌清茗 2021-02-07 22:51

I have a one to one field with django\'s users and UserInfo. I want to subscribe to the post_save callback function on the user model so that I can then save the UserInfo as wel

1条回答
  •  隐瞒了意图╮
    2021-02-07 23:28

    The error is caused by the user.user_info.save() line throwing an exception, and the transaction was flagged as broken (PostgreSQL enforces rolling back either the whole transaction, or to any savepoint stored before doing any more queries inside that transaction).

    You can rollback the transaction when an error occurs:

    from django.db import IntegrityError, transaction
    
    @receiver(post_save, sender=User) 
    def saveUserAndInfo(sender, instance, **kwargs):
        user = instance
        try:
            with transaction.atomic():
                user.user_info.save()
        except IntegrityError:
            info = UserInfo()
            info.user = user
            info.save()
    

    This is greatly described in the documentation.

    Also, note that catching all exception types is not generally the best idea as you might silence exceptions you weren't expecting.

    0 讨论(0)
提交回复
热议问题