class Skill(models.Model): name = models.CharField(max_length=50) description = models.TextField() class Developer(models.Model): name = models.CharField(max_length=50) skills = models.ManyToManyField(Skill, through='DeveloperSkill') class DeveloperSkill(models.Model): """具有相应能力和经验的开发人员技能。""" class Meta: order_with_respect_to = 'developer' """Sort skills per developer so that he can choose which skills to display on top for instance. """ unique_together = [ ('developer', 'skill'), ] """It's recommended that a together unique index be created on `(developer,skill)`. This is especially useful if your database is being access/modified from outside django. You will find that such an index is created by django when an explicit through model is not being used. """ ABILITY_CHOICES = [ (1, "Beginner"), (2, "Accustomed"), (3, "Intermediate"), (4, "Strong knowledge"), (5, "Expert"), ] developer = models.ForeignKey(Developer, models.CASCADE) skill = models.ForeignKey(Skill, models.CASCADE) """The many-to-many relation between both models is made by the above two foreign keys. Other fields (below) store information about the relation itself. """ ability = models.PositiveSmallIntegerField(choices=ABILITY_CHOICES) experience = models.PositiveSmallIntegerField(help_text="多年经验。")
建议在上创建一个唯一索引(developer,skill)。如果要从django外部访问/修改数据库,这将特别有用。您会发现,当不使用显式直通模型时,django会创建这样的索引。