首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否在M2M关系中使用直通模型

是否在M2M关系中使用直通模型
EN

Stack Overflow用户
提问于 2011-06-12 05:15:26
回答 2查看 147关注 0票数 5

我正在将用户的学历添加到他的用户配置文件中。用户可以具有针对其教育的多个条目。我是否应该使用基本的M2M关系,比如--

代码语言:javascript
运行
复制
class Education(models.Model):
    school = models.CharField(max_length=100)
    class_year = models.IntegerField(max_length=4, blank=True, null=True)
    degree = models.CharField(max_length=100, blank=True, null=True)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    educations = models.ManyToManyField(Education)

或者我应该对这种关系使用直通模型?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-12 05:36:55

@manji是正确的:不管你是否使用through,Django都会创建一个映射表。

要提供一个示例,说明为什么要向中间层或through表中添加更多字段:

您可以在through表中使用一个字段来跟踪该特定教育是否代表该人员所就读的最后一所学校:

代码语言:javascript
运行
复制
class Education(models.Model):
    ...

class UserProfile(models.Model):
    ...
    educations = models.ManyToManyField(Education, through='EduUsrRelation')

class EducationUserRelation(models.Model):
    education = models.ForeignKey(Education)
    user_profile = models.ForeignKey(UserProfile)
    is_last_school_attended = models.BooleanField()
票数 2
EN

Stack Overflow用户

发布于 2011-06-12 05:24:30

Django将使用create automatically an intermediary连接表来表示两个模型之间的ManyToMany关系。

如果你想添加更多的字段到这个表中,通过through属性提供你自己的表(即模型),否则你不需要这样做。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6318589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档