首页 > 解决方案 > IntegrityError:唯一约束失败:user_userprofile.user_id

问题描述

我定义了一个额外UserProfile的扩展User属性为

class UserProfile(models.Model):
    SEX = (
        (1, 'male'),
        (0, 'woman'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sex = models.IntegerField(choices=SEX, default=1)
    location = models.CharField(max_length=30)
    about_me = models.TextField()

当我将 UserProfile 附加到 Django shell 中的现有用户时

In[19]: for u in User.objects.all():
    ...:     profile = UserProfile(user=u)
    ...:     profile.save()

它报告错误:

IntegrityError: UNIQUE constraint failed: user_userprofile.user_id

我检查了答案Django: Integrity error UNIQUE constraint failed: user_profile.user_id - Stack Overflow,但没有解决我的问题的想法。

标签: django

解决方案


我喜欢 Jerin Peter George 的回答,因为它不会对数据库产生影响,但是,如果您在迭代此过程时需要访问用户配置文件实例,您还可以使用绑定到模型管理器的内置 get_or_create 方法。. IE。

for u in User.objects.all():
    instance, created = UserProfile.objects.get_or_create(
        user=u, 
        defaults={"""list of default keys and values"""})
    if created: 
        # update profile with form or other external data?
    else:
        # do other stuff 
    instance.save()

您还可以检查查询集的计数

user_profiles = UserProfile.objects.filter(user=u)
instance = None
if user_profiles.count() == 0:
    # user profile doesn't exist create one
    instance = UserProfile.objects.create(user=u)
else:
    # user profile exists
    instance = user_profiles.first()

推荐阅读