什么是 Django 查询集?
当我这样做时,
>>> b = Blog.objects.all()
>>> b
我得到这样的信息:
>>>[<Blog: Blog Title>,<Blog: Blog Tile>]
当我查询 b
是什么类型时,
>>> type(b)
我得到这样的信息:
>>> <class 'django.db.models.query.QuerySet'>
这是什么意思?它是像 dict
、list
等数据类型吗?
我将不胜感激如何构建像QuerySet
这样的数据结构的示例。
我想知道 Django 如何构建该QuerySet
(血淋淋的细节)。
When I do this,
>>> b = Blog.objects.all()
>>> b
I get this:
>>>[<Blog: Blog Title>,<Blog: Blog Tile>]
When I query what type b
is,
>>> type(b)
I get this:
>>> <class 'django.db.models.query.QuerySet'>
What does this mean? Is it a data type like dict
, list
, etc?
An example of how I can build data structure like a QuerySet
will be appreciated.
I would want to know how Django builds that QuerySet
(the gory details).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
django 查询集 就像它的名字所说的那样,基本上是 ( sql)查询,在上面的示例中
print(b.query)
将显示从 djangofilter
调用生成的 sql 查询。由于查询集是惰性,因此数据库查询不会立即完成,而是仅在以下情况下完成:需要 - 当查询集被评估时。例如,如果您在打印时调用它的
__str__
方法,如果您对它调用list()
,或者,最常见的是,您迭代它(用于 b.. 中的帖子
)。这种惰性应该可以帮助您避免执行不必要的查询,并且还允许您链接查询集和过滤器(您可以根据需要经常过滤查询集)。A django queryset is like its name says, basically a collection of (sql) queries, in your example above
print(b.query)
will show you the sql query generated from your djangofilter
calls.Since querysets are lazy, the database query isn't done immediately, but only when needed - when the queryset is evaluated. This happens for example if you call its
__str__
method when you print it, if you would calllist()
on it, or, what happens mostly, you iterate over it (for post in b..
). This lazyness should save you from doing unnecessary queries and also allows you to chain querysets and filters for example (you can filter a queryset as often as you want to).是的,这只是另一种类型,构建像所有其他类型。
Yes, it's just another type, built like every other type.
https://docs.djangoproject.com/en/1.8/topics/db /查询/
https://docs.djangoproject.com/en/1.8/topics/db/queries/
QuerySet 是给定模型的对象列表,QuerySet 允许您从数据库读取数据
A QuerySet is a list of objects of a given model, QuerySet allow you to read data from database