_set在Django中查询集 [英] _set in Django for a queryset

查看:190
本文介绍了_set在Django中查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

_set 对象可用。 //docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name rel = noreferrer> related_name 是未指定

The _set object is made available when related_name is not specified.

这篇关于_set在Django中查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆