2011-06-11 52 views
4

我正在将用户的教育添加到他的用户配置文件中。用户可能有多个条目用于他的教育。我是否应该使用基本的M2M关系,例如 -是否在M2M关系中使用直通模型

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) 

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

回答

2

@manji是正确的:无论您是否使用through,Django都会创建映射表。

提供的,为什么你可能要更多的字段添加到中介,或through表的例子:
你可以有在through表中的字段来跟踪特定的教育是否代表最终学校的人出席:

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

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

如果您想在此表中添加更多字段,请通过through属性提供您自己的表(即Model),否则您不需要。