Search code examples
djangodjango-modelsm2m

M2M django with more attributes


Im a bit confused about a M2M with django, I have the following issue:

Each user can has too many skills and per skill the user have to choose the time of experience. I mean, django-1 year, Heroku-3 years, and like this so on, how can I implement that in django?

My models:

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)

How can I fix my model to achieve that?


Solution

  • I will try to make it as simple as possible:

    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')
    

    And for user, if you mean the django authentication user, there is a way to extend it easily to be able to add specialities direct to the User model.