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.
@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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With