一对一关系,将外键放在主表或从表中?

时间:2014-04-01 02:17:24

标签: python django relationship

我有两张桌子(One-To-One关系):

class Member(models.Model):
    openid = models.CharField(max_length=32)
    realname = models.CharField(max_length=30, null=True, blank=True)
    nickname = models.CharField(max_length=32)
    join_date = models.DateField()
    ....more data ...


class MemberProfile(models.Model):
    member = models.ForeignKey(Member)
    position = models.ForeignKey(Position)
    mobile = models.CharField(max_length=50, null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    ....more data ...

显然,Member是主表,MemberProfile是奴隶 但我发现通过MemberProfile获取Member的数据很不方便。 如果Member有一个指向MemberProfile的ForeignKey链接,例如:

class Member(models.Model):
    profile = models.ForeignKey(MemberProfile)
    openid = models.CharField(max_length=32)
    realname = models.CharField(max_length=30, null=True, blank=True)
    nickname = models.CharField(max_length=32)
    join_date = models.DateField()
    ....more data ...

我可以更轻松地从会员处获取个人资料 member = Member.objects.get(id=id)
我可以通过member.profile而不是一句话来检索个人资料:profile = MemberProfile.objects.get(member=member)

Member ??

中移动ForeignKey定义是否更好?

2 个答案:

答案 0 :(得分:2)

为会员使用OnetoOneField

class MemberProfile:
    member = models.OneToOneField(Member)

然后您可以访问会员的个人资料,如下所示:

member.memberprofile

文档的相关引用:

  

从概念上讲,这类似于具有唯一= True的ForeignKey,但关系的“反向”将直接返回单个对象。

答案 1 :(得分:0)

根据您的型号。

class Member(models.Model):
    openid = models.CharField(max_length=32)
    ....more data ...


class MemberProfile(models.Model):
    member = models.ForeignKey(Member)
    position = models.ForeignKey(Position)
    ....more data ...

如果我们拥有MemberProfile对象

,那么获取Member数据并不是很不方便
member_object = Member.objects.get(id=1)
print member_object.memberprofile_set.all()     # here you can access MemberProfile 
                                                #data by using reverse relationship

您可以根据需要自定义结果,如下所示:

print member_object.memberprofile_set.filter(mobile='9717353657')
print member_object.memberprofile_set.filter(mobile='9717353657').values_list('email')

最好将Member模型作为主表。