Search code examples
sqldjangodatabasemodels

Django: Model Design, ManyToMany attribute fields?


Pretty new to working with databases in this way. I've got some sample code below. I've got the instrument object which will be a db listing of types of instruments, guitar, piano etc. Then the user object will have a ManyToMany on that so each user can have as many of those listed in their profile as they play.

What I'm stuck on is I'd like to have a field for experience with each of those instruments. Just not sure how to accomplish this without just static fields for how many instruments there would be (which since it's modifiable, could change). Thanks for any pointing in the correct direction.

class Instrument(models.Model):

    # Name of the instrument
    name = models.CharField(_('Name of Instrument'), blank=True, max_length=255)


    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

@python_2_unicode_compatible
class User(AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, max_length=255)
    zipcode = models.IntegerField(_('Zip Code of the User'), blank=True, null=True)
    instruments = models.ManyToManyField(Instrument)

Solution

  • Seems like a textbook use case for a through model with extra fields.

    class InstrumentExperience(models.Model):
        user = models.ForeignKey('User')
        instrument = models.ForeignKey('Instrument')
        experience = models.CharField(max_length=100)
    
    class User(AbstractUser):
        ...
        instruments = models.ManyToManyField('Instrument', through='InstrumentExperience')