如何解决如何使 Django OneToOne 关系在模型中独一无二
我有用户模型和 2 个配置文件模型(配置文件 A、配置文件 B)。 Profile 模型对 User 来说是一对一的,但是如何让 User 在两个 Profile 模型中都是唯一的?
class User():
name = CharField()
class ProfileA():
user = OneToOneField(User)
class ProfileB():
user = OneToOneField(User)
user = User.objects.create(name='abc')
profileA = ProfileA.objects.create(user=user)
profileB = ProfileB.objects.create(user=user)
问题是我可以使用相同的用户对象创建 profileA 和 profileB,但我想禁止。
解决方法
目前我有这个解决方案:
class ProfileA():
user = OneToOneField(User)
def save(self,*args,**kwargs):
if ProfileB.objects.filter(user=self.user).exists():
raise ValueError
super(ProfileA,self).save(*args,**kwargs)
class ProfileB():
user = OneToOneField(User)
def save(self,**kwargs):
if ProfileA.objects.filter(user=self.user).exists():
raise ValueError
super(ProfileB,**kwargs)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。