==========================
``QuerySet`` API reference
==========================
.. currentmodule:: django.db.models.query
This document describes the details of the ``QuerySet`` API. It builds on the
material presented in the :doc:`model </topics/db/models>` and :doc:`database
query </topics/db/queries>` guides, so you'll probably want to read and
understand those documents before reading this one.
Throughout this reference we'll use the :ref:`example blog models
<queryset-model-example>` presented in the :doc:`database query guide
</topics/db/queries>`.
.. _when-querysets-are-evaluated:
When ``QuerySet``\s are evaluated
=================================
Internally, a ``QuerySet`` can be constructed, filtered, sliced, and generally
passed around without actually hitting the database. No database activity
actually occurs until you do something to evaluate the queryset.
You can evaluate a ``QuerySet`` in the following ways:
* **Iteration.** A ``QuerySet`` is iterable, and it executes its database
query the first time you iterate over it. For example, this will print
the headline of all entries in the database::
for e in Entry.objects.all():
print(e.headline)
Note: Don't use this if all you want to do is determine if at least one
result exists. It's more efficient to use :meth:`~QuerySet.exists`.
* **Asynchronous iteration.**. A ``QuerySet`` can also be iterated over using
``async for``::
async for e in Entry.objects.all():
results.append(e)
Both synchronous and asynchronous iterators of QuerySets share the same
underlying cache.
.. versionchanged:: 4.1
Support for asynchronous iteration was added.
* **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
be sliced, using Python's array-slicing syntax. Slicing an unevaluated
``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django
will execute the database query if you use the "step" parameter of slice
syntax, and will return a list. Slicing a ``QuerySet`` that has been
evaluated also returns a list.
Also note that even though slicing an unevaluated ``QuerySet`` returns
another unevaluated ``QuerySet``, modifying it further (e.g., adding
more filters, or modifying ordering) is not allowed, since that does not
translate well into SQL and it would not have a clear meaning either.
* **Pickling/Caching.** See the following section for details of what
is involved when `pickling QuerySets`_. The important thing for the
purposes of this section is that the results are read from the database.
* **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
This is for convenience in the Python interactive interpreter, so you can
immediately see your results when using the API interactively.
* **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
This, as you might expect, returns the length of the result list.
Note: If you only need to determine the number of records in the set (and
don't need the actual objects), it's much more efficient to handle a count
at the database level using SQL's ``SELECT COUNT(*)``. Django provides a
:meth:`~QuerySet.count` method for precisely this reason.
* **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
it. For example::
entry_list = list(Entry.objects.all())
* **bool().** Testing a ``QuerySet`` in a boolean context, such as using
``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
to be executed. If there is at least one result, the ``QuerySet`` is
``True``, otherwise ``False``. For example::
if Entry.objects.filter(headline="Test"):
print("There is at least one Entry with the headline Test")
Note: If you only want to determine if at least one result exists (and don't
need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.
.. _pickling QuerySets:
Pickling ``QuerySet``\s
-----------------------
If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded
into memory prior to pickling. Pickling is usually used as a precursor to
caching and when the cached queryset is reloaded, you want the results to
already be present and ready for use (reading from the database can take some
time, defeating the purpose of caching). This means that when you unpickle a
``QuerySet``, it contains the results at the moment it was pickled, rather
than the results that are currently in the database.
If you only want to pickle the necessary information to recreate the
``QuerySet`` from the database at a later time, pickle the ``query`` attribute
of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
any results loaded) using some code like this::
>>> import pickle
>>> query = pickle.loads(s) # Assuming 's' is the pickled string.
>>> qs = MyModel.objects.all()
>>> qs.query = query # Restore the original 'query'.
The ``query`` attribute is an opaque object. It represents the internals of
the query construction and is not part of the public API. However, it is safe
(and fully supported) to pickle and unpickle the attribute's contents as
described here.
.. admonition:: Restrictions on ``QuerySet.values_list()``
If you recreate :meth:`QuerySet.values_list` using the pickled ``query``
attribute, it will be converted to :meth:`QuerySet.values`::
>>> import pickle
>>> qs = Blog.objects.values_list('id', 'name')
>>> qs
<QuerySet [(1, 'Beatles Blog')]>
>>> reloaded_qs = Blog.objects.all()
>>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
>>> reloaded_qs
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
.. admonition:: You can't share pickles between versions
Pickles of ``QuerySets`` are only valid for the version of Django that
was used to generate them. If you generate a pickle using Django
version N, there is no guarantee that pickle will be readable with
Django version N+1. Pickles should not be used as part of a long-term
archival strategy.
Since pickle compatibility errors can be difficult to diagnose, such as
silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
unpickle a queryset in a Django version that is different than the one in
which it was pickled.
.. _queryset-api:
``QuerySet`` API
================
Here's the formal declaration of a ``QuerySet``:
.. class:: QuerySet(model=None, query=None, using=None, hints=None)
Usually when you'll interact with a ``QuerySet`` you'll use it by
:ref:`chaining filters <chaining-filters>`. To make this work, most
``QuerySet`` methods return new querysets. These methods are covered in
detail later in this section.
The ``QuerySet`` class has the following public attributes you can use for
introspection:
.. attribute:: ordered
``True`` if the ``QuerySet`` is ordered — i.e. has an
:meth:`order_by()` clause or a default ordering on the model.
``False`` otherwise.
.. attribute:: db
The database that will be used if this query is executed now.
.. note::
The ``query`` parameter to :class:`QuerySet` exists so that specialized
query subclasses can reconstruct internal query state. The value of the
parameter is an opaque representation of that query state and is not
part of a public API.
.. currentmodule:: django.db.models.query.QuerySet
Methods that return new ``QuerySet``\s
--------------------------------------
Django provides a range of ``QuerySet`` refinement methods that modify either
the types of results returned by the ``QuerySet`` or the way its SQL query is
executed.
.. note::
These methods do not run database queries, therefore they are **safe to**
**run in asynchronous code**, and do not have separate asynchronous
versions.
``filter()``
~~~~~~~~~~
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
Django 文档¶ 你所需要知道的关于 Django 的一切。 快速入门¶ 你是刚学 Django 或是初学编程? 这就是你开始学习的地方! 从零开始: 概要 | 安装 入门教程: 第 1 节:请求和响应 | 第 2 节:模型和管理站点 | 第 3 节:视图和模板 | 第 4 节:表单和通用视图 | 第 5 节:测试 | 第 6 节:静态文件 | 第 7 节:自定义管理站点 进阶教程: 如何编写可复用的应用 | 提交你的第一个 Django 补丁 获取帮助¶ 遇到问题?我们可以帮你! 试试 FAQ —— 这里有很多常见问题的解答。 正在寻找特定的信息?试试 索引,模块索引 或者 详细内容目录。 找不到解决方案?去 FAQ:获取帮助 找找更多的帮助信息,也可以向社区寻求帮助。 在我们的 ticket tracker 报告关于 Django 的 Bug。 这份文档是如何组织的¶ Django 有丰富的文档。一份高度概述的文档会告诉你在哪里找到特定的东西: 教程 通过一系列的步骤来带领你创建一个网页应用程序。如果你是 Django 或网页应用开发的新手,可以从这里开始。也可以看一下
资源推荐
资源详情
资源评论
收起资源包目录
django4.1中文手册 (1192个子文件)
.buildinfo 230B
basic.css 14KB
djangodocs.css 7KB
reset-fonts-grids.css 5KB
pygments.css 5KB
homepage.css 892B
console-tabs.css 875B
fa-brands.min.css 630B
default.css 92B
fa-brands-400.eot 95KB
genindex.html 596KB
querysets.html 497KB
index.html 422KB
settings.html 377KB
database-functions.html 293KB
fields.html 292KB
builtins.html 289KB
tools.html 248KB
django-admin.html 241KB
gdal.html 233KB
queries.html 232KB
1.7.html 232KB
translation.html 230KB
1.8.html 229KB
api.html 215KB
fields.html 199KB
default.html 194KB
flattened-index.html 187KB
1.9.html 172KB
models.html 170KB
request-response.html 168KB
geos.html 167KB
1.10.html 166KB
expressions.html 163KB
modelforms.html 161KB
utils.html 152KB
1.4.html 151KB
1.6.html 150KB
security.html 146KB
cache.html 145KB
customizing.html 137KB
formsets.html 137KB
widgets.html 137KB
fields.html 131KB
checks.html 130KB
api.html 128KB
1.2.html 122KB
custom-template-tags.html 121KB
1.11.html 120KB
deprecation.html 118KB
instances.html 115KB
contents.html 107KB
3.1.html 107KB
databases.html 103KB
2.0.html 102KB
3.2.html 102KB
geoquerysets.html 101KB
syndication.html 101KB
advanced.html 101KB
auth.html 99KB
1.5.html 97KB
4.0.html 96KB
4.1.html 96KB
sessions.html 94KB
mixins.html 93KB
index.html 93KB
1.0-porting-guide.html 92KB
1.3.html 90KB
validators.html 90KB
tutorial.html 89KB
custom-model-fields.html 89KB
urls.html 88KB
generic-date-based.html 87KB
3.0.html 86KB
email.html 84KB
multi-db.html 81KB
sitemaps.html 80KB
migrations.html 80KB
functions.html 80KB
contenttypes.html 79KB
tutorial05.html 78KB
tutorial02.html 78KB
migration-operations.html 76KB
passwords.html 75KB
feedgenerator.html 74KB
aggregation.html 73KB
message.html 72KB
language.html 70KB
timezones.html 70KB
2.2.html 70KB
transactions.html 70KB
db-api.html 70KB
staticfiles.html 69KB
signals.html 68KB
templates.html 68KB
serialization.html 66KB
aggregates.html 65KB
options.html 63KB
storage.html 63KB
sync.html 63KB
共 1192 条
- 1
- 2
- 3
- 4
- 5
- 6
- 12
资源评论
hcucumber
- 粉丝: 0
- 资源: 17
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功