在 return 用户之后保存在数据库中?

saving in the database after return user?

这里我主要使用 Django 曲奇切割器,为了能够使用自定义形状标志进行保存,我必须以这种方式进行,它有效,我不确定这是正确的进行方式,但我只发现了这个一。我还使用 def Signup() 进行了测试,但没有结果但是我意识到用户没有直接保存在数据库中以进行此测试我在 alt_user 和 alt_user.name 之间放置了一个计时器。我注意到 User.object.get 给了我用户,我可以修改用户的其余信息。但是当我查看我的数据库时,用户的备份仅在用户 returns 之后进行。备份前是否缓存了用户?它提出的问题以及在保存 Alt_user.save() 之后我发送了一个 if 在 celery 任务中的 id 以进行更长的计算,在此先感谢您

User = get_user_model()

class CustomSignupForm(SignupForm):
    name = CharField( max_length=255)
    forename = CharField( max_length=255)
    street = CharField( max_length=255)
    street_number = IntegerField()
    city = CharField(max_length=255)
    country = CountryField().formfield()
    phone_number = IntegerField()
    date_of_birth = DateField()
    affiliate_link = IntegerField(required=False)
    class Meta:
        model = get_user_model()  # use this function for swapping user model

    def save(self, request):
        # Ensure you call the parent class's save.
        # .save() returns a User object.
        user = super(CustomSignupForm, self).save(request)
        alt_user = User.objects.get(pk=user.id)
        time.sleep(30)
        alt_user.name = self.cleaned_data['name']
        alt_user.forename = self.cleaned_data['forename']
        alt_user.street = self.cleaned_data['street']
        alt_user.street_number = self.cleaned_data['street_number']
        alt_user.city = self.cleaned_data['city']
        alt_user.country = self.cleaned_data['country']
        alt_user.phone_number = self.cleaned_data['phone_number']
        alt_user.date_of_birth = self.cleaned_data['date_of_birth']
        alt_user.save()
        calculate_user_in_matrix.delay(alt_user.id)
        return user

问题是您的代码在数据库事务中运行。如果您的 Celery worker 快速接手任务,则事务尚未提交。您刚刚创建的用户在提交之前在事务之外是不可见的。

解决方案是使用 django.db.transaction.on_commit 钩子:

from django.db import transaction

class CustomSignupForm(SignupForm):
    ...
    def save(self, request):
        ...
        alt_user.save()
        transaction.on_commit(calculate_user_in_matrix.s(alt_user.id).delay)