Django模型管理器事务和签名

2024-04-29 08:05:37 发布

您现在位置:Python中文网/ 问答频道 /正文

# The model
class UserManager(models.Manager):
    def create_user(self, temp_user_id):
        new_user = self.create(require data)
        # insert row to model B

# The model manager
class User(models.Model):
    # model fields

    objects = UserManager()

# Post save signal handler
def send_notification_to_user(sender, instance, created, **kwargs):
    # send sms notification to the newly created user


signals.post_save.connect(send_notification_to_user, sender=User)


# The view
class UserView(APIView):
    def post(self, request, format=None):
        try:
            with transaction.atomic():
                c_user = User.objects.create_user(request.data["temp_reg_id"])
                return Response(status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)

在这种情况下,如果一个用户注册了,那么用户会收到一条短信。但这里我运行的是事务中的模型管理器,所以如果#insert row to model B指令失败,那么所有数据库都将回滚。问题是在这种情况下用户会得到帐户创建短信,这是不正确的。我怎样才能克服这个问题?或者哪种方法更好?我的英语不好,你可以问我更多的解释。在


Tags: thetoselfsendmodelmodelsdefstatus