_set在Django中查询集 [英] _set in Django for a queryset
问题描述
在Django的 QuerySet
中如何使用 _set
有点困惑。例如,对象Blog b
和对象 Entry
与属性 entry_set <相关/ code>。
b.entry_set.all()
是什么意思?
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 by the attribute entry_set
. What is the meaning of b.entry_set.all()
?
如果有人可以使用此示例,我将不胜感激来显示可能的输出。
I would appreciate if someone could use this example to display the possible output.
推荐答案
您看到的是一个反向关联对象查找。
在您的示例中:
class Blog(models.Model):
pass
class Entry(..):
blog = Blog(..)
现在,给定对象 e
类型为条目
的用户,则可以执行 e.blog
来访问相关对象博客
-这是一个正向关系。
set
是django为您提供的反向查找类变量。
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.
因此,给定对象 b
-您会这样做:
So, given object b
- you would do:
entries = b.entry_set.all()
查询集反向的原因是,ForeignKey是 1-对多
关系。因此,相反是一个查询集。
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.
这篇关于_set在Django中查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!