我有两张桌子(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
??
答案 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
模型作为主表。