Search code examples
pythondjangodatabasemodelmany-to-many

Relationship between the client and the company


I have a problem with the relationship between the client and the company.

The requirement is this:

1) A client can be a client from many companies.

2) A company can have many clients.

class Company(models.Model):
    name = models.CharField(max_length=30)
    users = models.ManyToManyField('User')

    def __str__(self):
        return self.name


class User(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

I read that this should be a ManyToManyField relationship. But where should it be in the Company model or in the Client model?


Solution

  • I read that this should be a ManyToManyField relationship. But where should it be in the Company model or in the Client model?

    That does not matter. A many-to-many relation is stored in the database with an extra table that has foreign keys to both models. In your ManyToManyField you can give it a name for the relation in reverse:

    class Company(models.Model):
        name = models.CharField(max_length=30)
        clients = models.ManyToManyField('User', related_name='companies')
    
        def __str__(self):
            return self.name
    
    
    class User(models.Model):
        name = models.CharField(max_length=30)
    
        def __str__(self):
            return self.name

    You can query in both directions. For example:

    some_company.clients.all()

    is a QuerySet to obtain all clients of some_company, and:

    some_user.companies.all()

    is a QuerSet to obtain all companies ofsome_user`. There is no difference at all, since Django will automatically give the relation in reverse a name.