_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:

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)

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.

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

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

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

Tek Shinobi
Author: Tek Shinobi

Hiya Ninjas, I am the ninja who invented the fire, wheel, science, technology and everything intelligent this humanity has ever experienced since its evolution from monkeys and germs. Actually, above is a partial list. I also was involved with the Big Bang that created this universe. What was it like before the Big Bang is so secret that if I tell you, I will have to turn you into a hobbit and force you to be my gardener. Okay. Sayonanra, Namaste Tek Shinobi


Leave a Reply

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