django - 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,但没有解决我的问题的想法。
解决方案
我喜欢 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()
推荐阅读
- dbcontext - 无法创建“EcommerceContext”类型的对象。对于设计时支持的不同模式
- java - 方形对角线阵列
- python - Python:ParserError:错误标记数据。C 错误:字符串中的 EOF 从第 305768 行开始
- python-3.x - 如何在 tkinter 的文本小部件中获取一行字符?
- node.js - 如何检查用户是否已登录?Passport 和 discord oAuth2 (EJS)
- discord - 为什么 discord.py 无法正常运行?(设置)
- c - 指针/结构 free() - 堆损坏
- python - 在 Python 中的 dict 内的列表中搜索 - Pymongo
- javascript - 从构造函数中确定 tagName
- nginx - Nginx 代理通行证不渲染