2011-06-11 56 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),否則您不需要。