_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)
“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:
Thank you so much for this!
Thanks you so much for this!
Thank you so much!!!!!
Thanks bro! You saved my life…..