==========================
``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.
* **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:
.. code-block:: pycon
>>> 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`:
.. code-block:: pycon
>>> 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()``
~~~~~~~~~~~~
.. method:: filter(*args, **kwargs)
django的中文文档,不翻墙也可以使用的离线文档
需积分: 0 18 浏览量
更新于2024-06-22
收藏 6.71MB RAR 举报
Django是一款流行的Python Web框架,它提供了丰富的功能和灵活性,让开发者可以快速构建高效的Web应用程序。以下是关于Django中文文档的离线版内容概要、适用人群、适用场景及目标:
内容概要
Django中文文档的离线版主要包含以下几个部分:
教程:介绍如何使用Django框架创建一个简单的Web应用程序。
模型:详细说明Django的模型层,包括数据库模型定义、查询和操作等内容。
视图:介绍视图函数和类视图的使用方法,以及处理请求和生成响应的过程。
模板:指导开发者如何创建和使用Django模板,实现数据展示和页面渲染。
表单:解释Django表单的创建、验证和处理方式,以及常见表单组件的使用方法。
管理后台:介绍Django自带的管理后台功能,方便管理和操作数据库数据。
安全和认证:讨论Django中的用户认证和授权机制,以及常见的安全问题和防护措施。
部署和扩展:指导开发者如何将Django应用程序部署到生产环境,并介绍扩展Django的方法。
适用人群
Django中文文档的离线版适用于以下人群:
Django初学者:希望学习Django框架的基础知识和使用

#不吃香菜
- 粉丝: 440
- 资源: 12
最新资源
- 如何正确使用deepseek?99%的人都错了.zip
- 1000个DeepSeek神级提示词,让你轻松驾驭AI【赶紧收藏】.zip
- 3个DeepSeek隐藏玩法,99%的人都不知道!.zip
- X光手部小关节图像分类数据集(8000张图片).rar
- DeepSeek赋能职场-进阶(清华).7z
- DeepSeek从入门到精通(清华).7z
- 电气工程中X00110多机系统短路故障的时域仿真技术应用研究,X00110时域仿真技术:多机系统短路故障在电气工程领域的实际应用研究,X00110-多机系统短路故障后时域仿真技术在电气工程领域的应用
- DeepSeek+V3搭建个人知识库教程.zip
- Deepseek+V3从零基础到精通学习手册.zip
- DeepSeek+搞钱教程赚钱变现(0基础入门).zip
- DeepSeek+个万能公式.zip
- DeepSeek+实用万能提问模板.zip
- DeepSeek+提问攻略、使用实例和心得.zip
- DeepSeek-30个喂饭指令.zip
- DeepSeek+万能提问模板.zip
- DeepSeek-R1使用指南(简版).zip