When a model is related to another model via a foreign key or a many-to-many field, Django automatically generates an inverse relationship manager for that model. The name of this inverse relationship manager is _set
generated by appending the model class name. On the inverse relationship manager, you can use various query methods to access related objects.
Let's illustrate with an example. Let's say you have a Post
model and a Comment
model that can have multiple comments per post. In this case your model might look like this:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()
In the model, Django will automatically generate an inverse relationship manager Post
for you called . comment_set
You can use the relationship manager to access comment objects related to a particular post.
For example, to get all comments on a post, you can use the following code:
post = Post.objects.get(id=1)
comments = post.comment_set.all()
In the code above, the inverse relationship manager for all comment objects related to the object post.comment_set
is returned . post
By calling .all()
the method, you can get all related comment objects.
You can also use other query methods on the inverse relationship manager, such as .filter()
, , .exclude()
etc., to achieve more specific queries.