How to use the 'reverse' of a Django ManyToMany relationship?

DjangoDjango Models

Django Problem Overview


I'm coming from a Rails background, and am having a bit of trouble making use of the "Association Methods" provided in Django. I have two models (which have been simplified for the sake of brevity), like so:

class User(models.Model):
    username = models.CharField(max_length=100, unique=True)
    companies = models.ManyToManyField('Company', blank=True)

class Company(models.Model):
    name = models.CharField(max_length=255)

According to the Django documentation:

> "It doesn't matter which model has the ManyToManyField, but you should only put it in one of the models -- not both.".

So I understand that if I have an instance of a User, called user, I can do:

user.companies

My question is how do I do the reverse? How do I get all users that belong to a Company instance, let's say Company:

company.users # This doesn't work!

What's the convention to do this? The documentation that I've read doesn't really cover this. I need the association to work both ways, so I can't simply move it from one model to the other.

Django Solutions


Solution 1 - Django

company.user_set.all()

will return a QuerySet of User objects that belong to a particular company. By default you use modelname_set to reverse the relationship, but you can override this be providing a related_name as a parameter when defining the model, i.e.

class User(models.Model):
    companies = models.ManyToManyField(Company, ..., related_name="users")

> company.users.all()

here is the relevant documentation

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike TrpcicView Question on Stackoverflow
Solution 1 - DjangoTimmy O'MahonyView Answer on Stackoverflow