_set meaning in Django ORM relationship

_set is associated with reverse relation on a model.

Django allows you to access reverse relations on a model. By default, Django creates a manager (RelatedManager) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.

Excellent link on StackOverflow here:

If we have these models:

In Django,

“It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models — not both.”.

So, to get all the companies associated with a User, we can do:
But the reverse is a bit tricky. That is, how to get all users associated with a company.

Very easy. Get the reverse relationship using _set
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.

Then you can get the reverse without using _set like so:


Leave a Reply

Your email address will not be published. Required fields are marked *