【发布时间】:2012-12-29 23:57:33
【问题描述】:
如Extending the existing user model 所述,我创建了一个“配置文件”模型(与用户模型具有一对一的关系)。配置文件模型与另一个模型具有可选的多对一关系:
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True)
account = models.ForeignKey(Account, blank=True, null=True, on_delete=models.SET_NULL)
正如那里记录的那样,我还创建了一个内联管理员:
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'profiles'
# UserAdmin and unregister()/register() calls omitted, they are straight copies from the Django docs
现在,如果我在创建用户时未在管理员中选择 account,则不会创建配置文件模型。所以我connect 到post_save 信号,再次遵循文档:
@receiver(post_save, sender=User)
def create_profile_for_new_user(sender, created, instance, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
只要我这样做不在管理员中选择account,它就可以正常工作,但如果我这样做,我会得到一个IntegrityError 异常,告诉我duplicate key value violates unique constraint "app_profile_user_id_key" DETAIL: Key (user_id)=(15) already exists.
显然,内联管理员尝试自己创建 profile 实例,但我的 post_save 信号处理程序当时已经创建了它。
如何解决此问题,同时满足以下所有要求?
- 无论新用户如何创建,之后总会有一个
profile模型链接到它。 - 如果用户在创建用户时在管理员中选择了
account,则此account将在之后设置在新的profile模型上。如果不是,则字段为null.
环境:Django 1.5、Python 2.7
相关问题:
- Creating a extended user profile(症状相似,但原因不同)
【问题讨论】:
-
我也想知道使用
Profile.objects.get_or_create(user=instance)创建profile模型会不会更好? -
我遇到了同样的问题。我们正在使用 get_or_create,这似乎没有任何区别。
标签: python django django-models django-admin django-signals