问题描述
我正在将用户的教育程度添加到他的用户个人资料中。用户可能有多个用于其教育的条目。我是否应该使用基本的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,null=True)
class UserProfile(models.Model):
user = models.ForeignKey(User,unique=True)
educations = models.ManyToManyField(Education)
还是应该为此使用直通模型?谢谢。
解决方法
@manji是正确的:无论您是否使用
through
,Django都会创建一个映射表。
提供一个示例,说明为什么您可能想向中间表或“ 1”表添加更多字段:
您可以在“ 1”表中有一个字段来跟踪特定的教育是否代表该人就读的最后一所学校:
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()
, Django将自动创建一个中间联接表来表示两个模型之间的“ 5”关系。
如果要向此表添加更多字段,请通过through
属性提供自己的表(即模型),否则不需要。