Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether to use a through model in a M2M relationship

I am adding a user's education to his userprofile. A user may have multiple entries for his education. Should I be using a basic M2M relationship, such as --

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, blank=True, null=True)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    educations = models.ManyToManyField(Education)

Or should I be using a through model for this relationship? Thank you.

like image 759
David542 Avatar asked Oct 10 '22 18:10

David542


2 Answers

@manji is correct: Django will create a mapping table whether or not you use through.

To provide an example of why you might want to add more fields to the intermediary, or through table:
You could have a field in the through table to track whether or not that particular education represented the final school the person attended:

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()
like image 131
mechanical_meat Avatar answered Oct 14 '22 03:10

mechanical_meat


Django will create automatically an intermediary join table to represent the ManyToMany relation between the 2 models.

If you want to add more fields to this table, provide your own table (i.e Model) via through attribute, otherwise you don't need to.

like image 42
manji Avatar answered Oct 14 '22 01:10

manji