_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:
https://stackoverflow.com/questions/25386119/whats-the-difference-between-a-onetoone-manytomany-and-a-foreignkey-field-in-d

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:
User.companies.all()
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
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):
    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:
company.users.all()

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




5 Comments

Leave a Reply

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