I\'m a bit confused how to use _set
in a QuerySet
in Django. For example, an object Blog b
, and the object Entry
related
What you are seeing is a reverse related object lookup.
In your example:
class Blog(models.Model):
pass
class Entry(..):
blog = Blog(..)
Now, given object e
of type Entry
, you would do e.blog
to access the related object Blog
- which is a forward relation.
The _set
is a reverse lookup class variable django puts in for you.
So, given object b
- you would do:
entries = b.entry_set.all()
The reason the reverse is a queryset is, ForeignKey is 1-to-many
relationship. Hence, the reverse is a queryset.
The _set
object is made available when related_name is not specified.
Briefly speaking:
Suppose you have a model Car
and a model Wheel
. Wheel
has a foreign key relationship with Car
as follows:
class Car(models.Model):
pass
class Wheel(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE) # on_delete parameter is mandatory in Django 2.0
Let's say w
is an instance of Wheel
, and c
is an instance of Car
:
>>> w.car # returns the related Car object to w
>>> c.wheel_set.all() # returns all Wheel objects related to c
Detailed explanation
Using the models defined above, a Wheel
object w
can get its associated Car
object by accessing the car
attribute: w.car
.
If a model has a ForeignKey
, instances of that model will have access to the related foreign object via a simple attribute of the model.
According to the official Django documentation:
Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship.
In this case, a Car
object c
has access to a list of all related Wheel
objects via the wheel_set
attribute: c.wheel_set.all()
.
If a model has a ForeignKey
, instances of the foreign-key model will have access to a Manager
that returns all instances of the first model. By default, this Manager
is named FOO_set
, where FOO
is the source model name, lowercased. This Manager
returns QuerySets
, which can be filtered and manipulated.