M2M django具有更多属性

时间:2016-03-31 20:33:58

标签: django django-models m2m

我对使用django的M2M感到有点困惑,我有以下问题:

每个用户可以拥有太多的技能和技能,用户必须选择经验时间。我的意思是,django-1年,Heroku-3 years,像这样,我怎么能在django中实现呢?

我的模特:

class Specialities(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Experience(models.Model):
    specialities = models.ManyToManyField('self',through='RegisterProfessional',symmetrical = False)
    years = models.CharField(max_length=100)

    def __unicode__(self):
        return self.years

class RegisterProfessional(models.Model):
    id_document = models.OneToOneField(User)
    specialities = models.ForeignKey(Specialities)
    anios = models.ForeignKey(Experience)

如何修复模型以实现这一目标?

1 个答案:

答案 0 :(得分:2)

我会尽量让它变得简单:

class Speciality(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class User(models.Model):
    specialities = models.ManyToManyField('self',through='RegisterProfessional',symmetrical = False)


class RegisterProfessional(models.Model):
    id_document = models.ForeignKey(User)
    speciality = models.ForeignKey(Speciality)
    years = models.CharField(max_length=100)

    class Meta(object):
        unique_together = ('id_document', 'speciality')

对于用户而言,如果您指的是django身份验证用户,there is a way to extend it easily可以直接向User模型添加专业。