_set 在 Django 中用于查询集 [英] _set in Django for a queryset
问题描述
我有点困惑如何在 Django 的 QuerySet
中使用 _set
.例如,一个对象Blog b
,以及通过属性entry_set
关联的对象Entry
.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(..)
现在,给定 Entry
类型的对象 e
,您将执行 e.blog
来访问相关对象 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-to-many
关系.因此,反向是查询集.
The reason the reverse is a queryset is, ForeignKey is 1-to-many
relationship. Hence, the reverse is a queryset.
_set
对象在 related_name
未指定.
The _set
object is made available when related_name
is not specified.
这篇关于_set 在 Django 中用于查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!