[Django]-Many to Many or One to Many Django

3👍

First, is there a reason to extend the User model? The default model already includes a first_name and last_name field, so you don’t need an additional model just for that data. Similarly, you don’t really need CompanyContact because the User model also contains email and name (again, through first_name and last_name) fields.

You can add in your contacts as a ManyToManyField. If you want to use the custom Profile model instead of User, just replace User (in the ManyToManyField) with Profile.

class Company(models.Model):
    name = models.CharField(max_length=120)
    account_name = models.CharField(max_length=10, default="")
    sales_rep = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_sales", default="")
    csr = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_csr", default="")
    contacts = models.ManyToManyField(User) # or Profile

This allows each company to have many contacts and each user to be a contact of many companies – thus many-to-many.


Now, if you wanted extra data to describe the many-to-many relationship, you can have another model for that. For example, you may want to keep a record if the contact is still active or what their role is. So, you may have a CompanyContact model that is similar to:

class CompanyContact(models.Model):
    active = models.BooleanField(default=False)
    role = models.CharField(max_length=50, default="")
    user = models.ForeignKey(User) # or Profile
    company = models.ForeignKey(Company)

Then, declare the ManyToManyField relationship to use this new model:

class Company(models.Model):
    ...
    contacts = models.ManyToManyField(User, through="CompanyContact")
    # or contacts = models.ManyToManyField(Profile, through="CompanyContact")

Leave a comment