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

Dav*_*542 5 django django-models

我正在将用户的教育添加到他的用户资料中。一个用户可能有多个关于他的教育的条目。我是否应该使用基本的 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)
Run Code Online (Sandbox Code Playgroud)

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

ber*_*nie 2

@manji是正确的:无论你是否使用.Django都会创建一个映射表through

举一个例子来说明为什么您可能希望向中介或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()
Run Code Online (Sandbox Code Playgroud)