【问题标题】:Django: Associate objects before committingDjango:在提交之前关联对象
【发布时间】:2017-05-15 14:47:01
【问题描述】:

所以我正在加载一个 djang-registration 表单,我将其子类化,以便创建两个相关对象,一个 GeneralUser 和他们的业务。以下代码失败并显示警告:

save() 被禁止以防止由于未保存的相关对象“所有者”而导致数据丢失。

当我尝试创建这样的业务时,我也收到了“NoneType 对象没有属性所有者”“NoneType”对象没有属性“is_active””的警告:business = Business(name=self.cleaned_data['business_name'], owner=user)

我只是在寻找一种不向用户或企业提交 db 的方法,除非我同时这样做。请注意,我确实没有查看此表单以检查各种事情,因为 django-registration 正在处理所有这些查看。

class GeneralUserForm(UserCreationForm):
    business_name = forms.CharField(required=True)

    class Meta:
        model = GeneralUser
        fields = ['username', 'email', 'password1',
                  'password2', 'business_name']

    def save(self, commit=True):
        user = super(GeneralUserForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        business = Business.objects.create(name=self.cleaned_data['business_name'], owner=user)

        if commit:
            user.is_active = True  # TODO: remove before deployment.
            user.save()
            business.save()
            return user

我将如何将GeneralUserBusiness 关联,然后才提交到数据库?

【问题讨论】:

  • 检查用户是否有属性'id',如果有则可以提交业务。
  • @pramod 但是用户在数据库中创建之前没有id 属性?

标签: python django django-registration


【解决方案1】:

如果你想这样做,那么首先你应该保存用户然后创建业务对象。除非您已提交到数据库,否则您不能将用户实例与业务对象相关联。关联实际上是与用户对象的主键的关系,只有在提交到数据库时才会创建。 只有在用户对象提交之后,业务对象才能被保存。

你可以这样做,

def save(self, commit=True, *args, **kwargs): 
    user = super(GeneralUserForm, self).save(*args, **kwargs)
    user.set_password(self.cleaned_data["password1"]) 
    business = Business(name=self.cleaned_data['business_name'])

    if commit:
        user.is_active = True
        user.save()
        business.owner = user
        business.save()
        return user

【讨论】:

  • 我想我试过了,但它不起作用。它抱怨是因为当我们尝试关联关系时,用户没有保存在数据库中。
  • 这会返回错误NoneType' object has no attribute 'is_active'
  • 再次编辑答案。
  • 能否在调用超级保存方法后打印用户并检查是否保存。
猜你喜欢
  • 2014-09-22
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2012-04-01
相关资源
最近更新 更多