ID English原文 中文翻译 最近翻译记录 状态 操作
0#翻译
Appendix C: Database API Reference
----------------------------------
附录C 数据库API参考
----------------------------------
1482天前 翻译
1#翻译
Djangos database API is the other half of the model API discussed in Appendix B. Once youve
defined a model, youll use this API any time you need to access the database. Youve seen
examples of this API in use throughout the book; this appendix explains all the various
options in detail.
Django数据库API是附录B中讨论过的数据模型API的另一部分。一旦定义了数据模型,你将会在任何要访问数据库的时候使用数据库API。你已经在本书中看到了很多数据库API的例子,这篇附录对数据库API的各种变化详加阐释。
1424天前 翻译
2#翻译
Like the model APIs discussed in Appendix B, though these APIs are considered very stable,
the Django developers consistently add new shortcuts and conveniences. Its a good idea to
always check the latest documentation online, available at
`http://www.djangoproject.com/documentation/0.96/db-api/`_.
和附录B中讨论的数据模型API时一样,尽管认为这些API已经很稳定,Django开发者一直在增加各种便捷方法。因此,查看最新的在线文档是个好方法,在线文档可以在  `http://www.djangoproject.com/documentation/0.96/db-api/`_ 找到.
1246天前 翻译
3#翻译
Throughout this reference, well refer to the following models, which might form a simple
Weblog application:
贯穿这个参考文档,我们都会提到下面的这个models。它或许来自于一个简单的博客程序。
1348天前 翻译
6#翻译
Creating Objects
````````````````
创建对象
````````````````
1389天前 翻译
7#翻译
To create an object, instantiate it using keyword arguments to the model class, and then
call ``save()`` to save it to the database:
要创建一个对象, 用模型类使用关键字参数实例化它, 接着调用 ``save()``  将它保存到数据库中:
1389天前 翻译
10#翻译
This performs an ``INSERT`` SQL statement behind the scenes. Django doesnt hit the database
until you explicitly call ``save()`` .
这会在后台执行一个SQL语句.  如果您不显式地调用 ``save()`` , Django不会保存到数据库.
1389天前 翻译
11#翻译
The ``save()`` method has no return value.
``save()`` 方法没有返回值.
1389天前 翻译
12#翻译
To create an object and save it all in one step see the ``create`` manager method discussed
shortly.
要在一个步骤中创建并保存一个对象, 参见会稍后讨论的 ``create`` 管理者方法, 
1389天前 翻译
13#翻译
What Happens When You Save?
'''''''''''''''''''''''''''
当您保存的时候发生了什么?
'''''''''''''''''''''''''''
1389天前 翻译
14#翻译
When you save an object, Django performs the following steps:
当您保存一个对象的时候, Django执行下面的步骤:
799天前 翻译
15#翻译
    **Emit a pre_save signal.** This provides a notification that an object is about to be
    saved. You can register a listener that will be invoked whenever this signal is emitted.
    These signals are still in development and werent documented when this book went to
    press; check the online documentation for the latest information.
    **发出一个预存信号。** 它发出一个将要存储一个对象的通知。你可以注册一个监听程序,在信号发出的时候就会被调用。到本书出版时,这些信号仍在开发中并且没有文档化,请查看在线文档来获得最新的消息。
1261天前 翻译
16#翻译
    **Preprocess the data.** Each field on the object is asked to perform any automated data
    modification that the field may need to perform.
    **预处理数据.** 对于对象的每个字段,将根据需要进行自动的数据修改。
1261天前 翻译
17#翻译
    Most fields do *no* preprocessing the field data is kept as is. Preprocessing is only
    used on fields that have special behavior, like file fields.
    大部分字段并不预处理,它们会保持它们原来的样子。预处理仅仅用在那些有特殊性质的字段,比如文件字段。
1261天前 翻译
18#翻译
    **Prepare the data for the database.** Each field is asked to provide its current value
    in a data type that can be written to the database.
    **为数据库准备数据。** 每一个字段先要把当前值转化成数据库中可以保存的数据的类型。
1261天前 翻译
19#翻译
    Most fields require no data preparation. Simple data types, such as integers and
    strings, are ready to write as a Python object. However, more complex data types often
    require some modification. For example, ``DateFields`` use a Python ``datetime`` object
    to store data. Databases dont store ``datetime`` objects, so the field value must be
    converted into an ISO-compliant date string for insertion into the database.
    大多数字段的数据不需要预先准备。简单的数据类型,比如整型和字符串等python对象可以直接写进数据库。然而,更复杂的数据类型需要做一些修改。比如, ``DateFields`` 使用python的 ``datetime`` 对象来存储数据。数据库并不能存储 ``datetime`` 对象,所以该字段要存入数据库先要把值转化为符合ISO标准的日期字符串。
1261天前 翻译
20#翻译
    **Insert the data into the database.** The preprocessed, prepared data is then composed
    into an SQL statement for insertion into the database.
    **向数据库中插入数据。** 经过预处理准备好的数据然后会组合成一条SQL语句来插入数据库。
1261天前 翻译
21#翻译
    **Emit a post_save signal.** As with the ``pre_save`` signal, this is used to provide
    notification that an object has been successfully saved. Again, these signals are not
    yet documented.
    **发出存毕信号。** 与预存信号类似,存毕信号在对象成功保存之后发出。同样,这些信号也还没有文档化。
1261天前 翻译
22#翻译
Autoincrementing Primary Keys
'''''''''''''''''''''''''''''
自增主键
''''''''
1261天前 翻译
23#翻译
For convenience, each model is given an autoincrementing primary key field named ``id``
unless you explicitly specify ``primary_key=True`` on a field (see the section titled
AutoField in Appendix B).
为了方便,每个数据库模型都会添加一个自增主键字段,即 ``id`` 。除非你在某个字段属性中显式的指定 ``primary_key=True`` (参见附录B中题为AutoField的章节)。
1261天前 翻译
24#翻译
If your model has an ``AutoField`` , that autoincremented value will be calculated and saved
as an attribute on your object the first time you call ``save()`` :
如果你的数据库模型中包括 ``AutoField`` ,这个自增量的值将会在你第一次调用 ``save()`` 时作为对象的一个属性计算得出并保存起来。
1261天前 翻译
27#翻译
Theres no way to tell what the value of an ID will be before you call ``save()`` , because
that value is calculated by your database, not by Django.
在调用 ``save()`` 方法之前没有办法知道ID的值,因为这个值是数据库计算出来的,不是Django。
1261天前 翻译
28#翻译
If a model has an ``AutoField`` but you want to define a new objects ID explicitly when
saving, just define it explicitly before saving, rather than relying on the autoassignment
of the ID:
如果你想在一个新数据存储时,定义其 ``AutoField`` 字段值,而不依赖于数据库自动分配,明确赋值即可。
1261天前 翻译
31#翻译
If you assign auto-primary-key values manually, make sure not to use an already existing
primary key value! If you create a new object with an explicit primary key value that
already exists in the database, Django will assume youre changing the existing record rather
than creating a new one.
如果你手动指定自增主键的值,要确保这个主键在数据库中不存在!如果你显式地指定主键来创建新对象,而这个主键在数据库中已经存在的话,Django会认为你要更改已经存在的那条记录,而不是创建一个新的。
1261天前 翻译
32#翻译
Given the preceding ``'Cheddar Talk'`` blog example, this example would override the
previous record in the database:
以前面的 ``'Cheddar Talk'`` blog为例,下面的例子会覆盖数据库中已经存在的记录:
1261天前 翻译
35#翻译
Explicitly specifying auto-primary-key values is mostly useful for bulk-saving objects, when
youre confident you wont have primary key collision.
如果你确信不会产生主键冲突的话,当需要保存大量对象的时候,明确指定自增主键的值是非常有用的。
1261天前 翻译
36#翻译
Saving Changes to Objects
`````````````````````````
保存对对象做的修改
``````````````````
1261天前 翻译
37#翻译
To save changes to an object thats already in the database, use ``save()`` .
要保存一个已经在数据库中存在的对象的变更, 使用 ``save()`` .
1389天前 翻译
38#翻译
Given a ``Blog`` instance ``b5`` that has already been saved to the database, this example
changes its name and updates its record in the database:
假定 ``b5`` 这个 ``Blog`` 实例已经保存到数据库中,下面这个例子更改了它的名字,并且更新了它在数据库中的记录:
1261天前 翻译
41#翻译
This performs an ``UPDATE`` SQL statement behind the scenes. Again, Django doesnt hit the
database until you explicitly call ``save()`` .
这个例子在后台执行了 ``UPDATE`` 这一SQL语句。再次声明,Django在你显式地调用 ``save()`` 之前是不会更新数据库的。
1261天前 翻译
42#翻译
How Django Knows When to ``UPDATE`` and When to ``INSERT``
Django如何得知何时 ``UPDATE`` ,何时 ``INSERT`` 呢
1261天前 翻译
43#翻译
You may have noticed that Django database objects use the same ``save()`` method for
creating and changing objects. Django abstracts the need to use ``INSERT`` or ``UPDATE`` SQL
statements. Specifically, when you call ``save()`` , Django follows this algorithm:
你可能已经注意到Django数据库对象在创建和更改对象时,使用了同一个 ``save()`` 函数。Django抽象化了对SQL语句中的 ``INSERT`` 和 ``UPDATE`` 的需求,当你调用 ``save()`` 的时候,Django会遵守下面的原则:
1261天前 翻译
44#翻译
*   If the objects primary key attribute is set to a value that evaluates to ``True`` (i.e.,
    a value other than ``None`` or the empty string), Django executes a ``SELECT`` query to
    determine whether a record with the given primary key already exists.
*   如果对象的主键属性被设置成相当于 ``True`` 的值(比如 ``None`` 或者空字符串之外的值),Django会执行一个 ``SELECT`` 查询来检测是否已存在一个相同主键的记录。
1261天前 翻译
45#翻译
*   If the record with the given primary key does already exist, Django executes an
    ``UPDATE`` query.
*   如果已经存在一个主键相同的记录,Django就执行 ``UPDATE`` 查询。
1261天前 翻译
46#翻译
*   If the objects primary key attribute is *not* set, or if its set but a record doesnt
    exist, Django executes an ``INSERT`` .
*   如果对象的主键属性 *没有* 被设置,或者被设置但数据库中没有与之同主键的记录,那么Django就会执行 ``INSERT`` 查询。
1261天前 翻译
47#翻译
Because of this, you should be careful not to specify a primary key value explicitly when
saving new objects if you cannot guarantee the primary key value is unused.
正因如此,如果你不能确信数据库中不存在主键相同的记录的话,你应该避免没有明确指定主键的值。
1261天前 翻译
48#翻译
Updating ``ForeignKey`` fields works exactly the same way; simply assign an object of the
right type to the field in question:
更新 ``ForeignKey`` 字段原理是一样的,只是要给这个字段赋予正确类型的对象就行了。
1249天前 翻译
51#翻译
Django will complain if you try to assign an object of the wrong type.
如果你把一个错误类型的对象赋给它,Django会警报的。
1261天前 翻译
52#翻译
Retrieving Objects
``````````````````
获取对象
``````````````````
1389天前 翻译
53#翻译
Throughout the book youve seen objects retrieved using code like the following:
在这本书中,获取对象都使用下面这样的代码实现的:
1261天前 翻译
56#翻译
There are quite a few moving parts behind the scenes here: when you retrieve objects from
the database, youre actually constructing a ``QuerySet`` using the models ``Manager`` . This
``QuerySet`` knows how to execute SQL and return the requested objects.
在这幕后会有相当多的步骤:当你从数据库中获取对象的时候,你实际上用 ``Manager`` 模块构造了一个 ``QuerySet`` ,这个 ``QuerySet`` 知道怎样去执行SQL语句并返回你想要的对象。
1261天前 翻译
57#翻译
Appendix B looked at both of these objects from a model-definition point of view; now well
look at how they operate.
附录B从模块定义的角度讨论了这两个对象,现在让我们研究一下它们是怎么工作的。
1261天前 翻译
58#翻译
A ``QuerySet`` represents a collection of objects from your database. It can have zero, one,
or many *filters* criteria that narrow down the collection based on given parameters. In SQL
terms, a ``QuerySet`` equates to a ``SELECT`` statement, and a filter is a limiting clause
such as ``WHERE`` or ``LIMIT`` .
``QuerySet`` 代表了你的数据库中的对象的一个集合。它根据所给参数可以构造若干个 *过滤器* 来缩小这个集合的规模。用SQL术语来讲,一个 ``QuerySet`` 就相当于一个 ``SELECT`` 语句,过滤器相当于诸如 ``WHERE`` 或者 ``LIMIT`` 的限定语。
1261天前 翻译
59#翻译
You get a ``QuerySet`` by using your models ``Manager`` . Each model has at least one
``Manager`` , and its called ``objects`` by default. Access it directly via the model class,
like so:
你通过模块的 ``Manager`` 就可以得到一个 ``QuerySet`` 。每个模块至少有一个 ``Manager`` ,默认名称是 ``objects`` 。可以通过模块类来直接访问它,比如:
1261天前 翻译
62#翻译
``Manager`` s are accessible only via model classes, rather than from model instances, to
enforce a separation between table-level operations and record-level operations:
为了强制分离数据表级别的操作和数据记录级别的操作, ``Manager`` 只能通过模块类而不是模块实例来访问:
1261天前 翻译
65#翻译
The ``Manager`` is the main source of ``QuerySets`` for a model. It acts as a root
``QuerySet`` that describes all objects in the models database table. For example,
``Blog.objects`` is the initial ``QuerySet`` that contains all ``Blog`` objects in the
database.
对一个模块来讲, ``Manager`` 是 ``QuerySets`` 的主要来源。它就像一个根本的 ``QuerySet`` ,可以对模块的数据库表中的所有对象进行描述。比如, ``Blog.objects`` 就是包含着数据库中所有的 ``Blog`` 对象的一个根本的 ``QuerySet`` 。
1261天前 翻译
66#翻译
Caching and QuerySets
`````````````````````
缓存与查询集
````````````
1248天前 翻译
67#翻译
Each ``QuerySet`` contains a cache, to minimize database access. Its important to understand
how it works, in order to write the most efficient code.
为了减少数据库访问次数,每个 ``QuerySet`` 包含一个缓存,要写出高效的代码,理解这一点很重要。
1248天前 翻译
68#翻译
In a newly created ``QuerySet`` , the cache is empty. The first time a ``QuerySet`` is
evaluated and, hence, a database query happens Django saves the query results in the
``QuerySet`` s cache and returns the results that have been explicitly requested (e.g., the
next element, if the ``QuerySet`` is being iterated over). Subsequent evaluations of the
``QuerySet`` reuse the cached results.
在刚被创建的 ``QuerySet`` 中,缓存是空的。当 ``QuerySet`` 第一次被赋值,就是执行数据库查询的时候,Django会把查询结果保存到这个 ``QuerySet`` 的缓存中,并返回请求结果(例如, ``QuerySet`` 迭代结束的时候,就会返回下一条记录)。再次使用 ``QuerySet`` 的值的话会重复使用缓存中的内容。
1248天前 翻译
69#翻译
Keep this caching behavior in mind, because it may bite you if you dont use your
``QuerySet``s correctly. For example, the following will create two ``QuerySet`` s, evaluate
them, and throw them away:
要时刻记住这种缓存机制,因为如果你不正确的使用 ``QuerySet`` 的话,可能会遇到麻烦。例如,下面这段代码会分别产生两个 ``QuerySet`` ,计算出来然后丢弃。
1248天前 翻译
72#翻译
That means the same database query will be executed twice, effectively doubling your
database load. Also, theres a possibility the two lists may not include the same database
records, because an ``Entry`` may have been added or deleted in the split second between the
two requests.
这就意味着相同的数据库的查询会被执行两次,使数据库的负载加倍。而且这两个列表包含的数据可能不同,因为在两次查询的间隙,可能有一个 ``Entry`` 被添加或是删除了。
1248天前 翻译
73#翻译
To avoid this problem, simply save the ``QuerySet`` and reuse it:
避免这个问题,简单的方法是保存这个 ``QuerySet``  并且重用它。
1249天前 翻译
76#翻译
Filtering Objects
`````````````````
过滤器对象
``````````
1248天前 翻译
77#翻译
The simplest way to retrieve objects from a table is to get all of them. To do this, use the
``all()`` method on a ``Manager`` :
从数据表中获取对象的最简单的方法就是得到所有的对象,就是调用一个 ``Manager`` 的 ``all()`` 方法。
919天前 翻译
80#翻译
The ``all()`` method returns a ``QuerySet`` of all the objects in the database.
``all()`` 方法返回一个包含数据库的所有对象的 ``QuerySet`` 。
1248天前 翻译
81#翻译
Usually, though, youll need to select only a subset of the complete set of objects. To
create such a subset, you refine the initial ``QuerySet`` , adding filter conditions. Youll
usually do this using the ``filter()`` and/or ``exclude()`` methods:
但是通常情况下,只需要从所有对象中请求一个子集,这就需要你细化一下刚才的 ``QuerySet`` ,加一些过滤条件。用 ``filter()`` 和 ``exclude()`` 方法可以实现这样的功能:
1248天前 翻译
84#翻译
``filter()`` and ``exclude()`` both take *field lookup* arguments, which are discussed in
detail shortly.
``filter()`` 和 ``exclude()`` 方法都接受 *字段查询* 参数,我们稍后会详细讨论。
1248天前 翻译
85#翻译
Chaining Filters
''''''''''''''''
级联过滤器
''''''''''''''''
1389天前 翻译
86#翻译
The result of refining a ``QuerySet`` is itself a ``QuerySet`` , so its possible to chain
refinements together, for example:
细化过的 ``QuerySet`` 本身就是一个 ``QuerySet`` ,所以可以进一步细化,比如:
1248天前 翻译
89#翻译
This takes the initial ``QuerySet`` of all entries in the database, adds a filter, then an
exclusion, and then another filter. The final result is a ``QuerySet`` containing all
entries with a headline that starts with What that were published between January 1, 2005,
and the current day.
这样,我们把最初过的数据库中所有内容的一个 ``QuerySet`` 经过添加一个过滤器、一个反向过滤器和另外一个过滤器,得到一个最终的 ``QuerySet`` ,最终结果中包含了所有标题以“What”开头的2005年至今的出版的条目。
1248天前 翻译
90#翻译
Its important to point out here that ``QuerySets`` are lazy the act of creating a
``QuerySet`` doesnt involve any database activity. In fact, the three preceding lines dont
make *any* database calls; you can chain filters together all day long and Django wont
actually run the query until the ``QuerySet`` is *evaluated* .
这里需要指出的一点是,创建一个 ``QuerySet`` 并不会牵涉到任何数据库动作。事实上,上面的三行并不会产生 *任何的* 数据库调用。就是说你可以连接任意多个过滤器,只要你不把这个 ``QuerySet`` 用于赋值的话,Django是不会执行查询的。
1248天前 翻译
91#翻译
You can evaluate a ``QuerySet`` in any following ways:
你可以用下面的方法来计算 ``QuerySet`` 的值:
1248天前 翻译
92#翻译
    *Iterating* : A ``QuerySet`` is iterable, and it executes its database query the first
    time you iterate over it. For example, the following ``QuerySet`` isnt evaluated until
    its iterated over in the ``for`` loop:
    *迭代* : ``QuerySet`` 是可以迭代的,它会在迭代结束的时候执行数据库查询。例如,下面的这个 ``QuerySet`` 在for循环迭代完毕之前,是不会被赋值的:
1248天前 翻译
95#翻译
    This prints all headlines from 2006 that contain bill but causes only one database hit.
    它会打印2006年所有包含bill的标题,但只会触发一次数据库访问。
1248天前 翻译
96#翻译
    *Printing it* : 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.
    *打印* :对 ``QuerySet`` 使用 ``repr()`` 方法时,它是会被赋值的。这是为了方便Python的交互解释器,这样在交互环境中使用API时就会立刻看到结果。
1248天前 翻译
97#翻译
    *Slicing* : As explained in the upcoming Limiting QuerySets section, a ``QuerySet`` can
    be sliced using Pythons array-slicing syntax. Usually slicing a ``QuerySet`` returns
    another (unevaluated)``QuerySet``, but Django will execute the database query if you use
    the step parameter of slice syntax.
    *切片* : 在接下来的“限量查询集”一节中就会解释这一点, ``QuerySet`` 是可以用Python的数组切片的语法来切片的。通常切片过的 ``QuerySet`` 会返回另外一个(尚未赋值的) ``QuerySet`` ,但是如果在切片时使用步长参数的话,Django会执行数据库查询的。
1248天前 翻译
98#翻译
    *Converting to a list* : You can force evaluation of a ``QuerySet`` by calling
    ``list()`` on it, for example:
    *转化成列表* :对 ``QuerySet`` 调用 ``list()`` 方法的话,就可以对它强制赋值,比如:
1248天前 翻译
101#翻译
    Be warned, though, that this could have a large memory overhead, because Django will
    load each element of the list into memory. In contrast, iterating over a ``QuerySet``
    will take advantage of your database to load data and instantiate objects only as you
    need them.
    但是,需要警告的是这样做会导致很大的内存负载,因为Django会把列表的每一个元素加载到内存。相比之下,对 ``QuerySet`` 进行迭代会利用数据库来加载数据,并且在需要的时候才会把对象实例化。
1248天前 翻译
102#翻译
Filtered QuerySets Are Unique
过滤过的查询集是独一无二的
1248天前 翻译
103#翻译
Each time you refine a ``QuerySet`` , you get a brand-new ``QuerySet`` that is in no way
bound to the previous ``QuerySet`` . Each refinement creates a separate and distinct
``QuerySet`` that can be stored, used, and reused:
你每次细化一个 ``QuerySet`` 都会得到一个崭新的 ``QuerySet`` ,绝不会与之前的 ``QuerySet`` 有任何的瓜葛。每次的细化都会创建一个各自的截然不同的 ``QuerySet`` ,可以用来存储、使用和重用。
1088天前 翻译
106#翻译
These three ``QuerySets`` are separate. The first is a base ``QuerySet`` containing all
entries that contain a headline starting with What. The second is a subset of the first,
with an additional criterion that excludes records whose ``pub_date`` is greater than now.
The third is a subset of the first, with an additional criterion that selects only the
records whose ``pub_date`` is greater than now. The initial ``QuerySet`` (``q1`` ) is
unaffected by the refinement process.
这三个 ``QuerySet`` 是无关的。第一个基础查询集包含了所有标题以What开始的条目。第二个查询集是第一个的子集,只是过滤掉了 ``pub_date`` 比当前时间大的记录。第三个查询集也是第一个的子集,只保留 ``pub_date`` 比当前时间大的记录。初始的 ``QuerySet`` ( ``q1`` )是不受细化过程的影响。
1248天前 翻译
107#翻译
Limiting QuerySets
''''''''''''''''''
限量查询集
''''''''''
1248天前 翻译
108#翻译
Use Pythons array-slicing syntax to limit your ``QuerySet`` to a certain number of results.
This is the equivalent of SQLs ``LIMIT`` and ``OFFSET`` clauses.
可以用Python的数据切片的语法来限定 ``QuerySet`` 的结果数量,这和SQL中的 ``LIMIT`` 和 ``OFFSET`` 语句是一样的。
1248天前 翻译
109#翻译
For example, this returns the first five entries (``LIMIT 5`` ):
比如,这句返回前五个条目( ``LIMIT 5`` ):
1248天前 翻译
112#翻译
This returns the sixth through tenth entries (``OFFSET 5 LIMIT 5`` ):
这句返回第六到第十个条目( ``OFFSET 5 LIMIT 5`` ):
1248天前 翻译
115#翻译
Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` it doesnt evaluate the query.
An exception is if you use the step parameter of Python slice syntax. For example, this
would actually execute the query in order to return a list of every *second* object of the
first ten:
一般地,对 ``QuerySet`` 进行切片会返回一个新的 ``QuerySet`` ,但并不执行查询。如果你在Python切片语法中使用步长参数的话,就会出现特例。例如,要返回前十个对象中的偶序数对象的列表时,实际上会执行查询:
1248天前 翻译
118#翻译
To retrieve a *single* object rather than a list (e.g., ``SELECT foo FROM bar LIMIT 1`` ),
use a simple index instead of a slice. For example, this returns the first ``Entry`` in the
database, after ordering entries alphabetically by headline:
要得到 *单个* 对象而不是一个列表时(例如 ``SELECT foo FROM bar LIMIT 1`` ),可以不用切片而是使用下标。例如,这样就会返回数据库中对标题进行字母排序后的第一个 ``Entry`` :
1248天前 翻译
121#翻译
This is roughly equivalent to the following:
刚才这句和下面的大致相当:
1248天前 翻译
124#翻译
Note, however, that the first of these will raise ``IndexError`` while the second will raise
``DoesNotExist`` if no objects match the given criteria.
但是要记住,如果没有符合条件的记录的话,第一种用法会导致 ``IndexError`` ,而第二种用法会导致 ``DoesNotExist`` 。
1248天前 翻译
125#翻译
Query Methods That Return New QuerySets
'''''''''''''''''''''''''''''''''''''''
返回新的 QuerySets 的 查询方法
'''''''''''''''''''''''''''''''''''''''
1389天前 翻译
126#翻译
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. These methods are
described in the sections that follow. Some of the methods take field lookup arguments,
which are discussed in detail a bit later on.
Django提供了一系列的 ``QuerySet`` 细化方法,既可以修改 ``QuerySet`` 返回的结果的类型,又可以修改对应的SQL查询的执行方法。这就是这一节我们要讨论的内容。其中有一些细化方法会接收字段查询参数,我们稍后会详细讨论。
1247天前 翻译
127#翻译
filter(\*\*lookup)
..................
filter(\*\*lookup)
..................
1248天前 翻译
128#翻译
Returns a new ``QuerySet`` containing objects that match the given lookup parameters.
返回一个新的 ``QuerySet`` ,包含匹配参数lookup的对象。
1248天前 翻译
129#翻译
exclude(\*\*kwargs)
...................
exclude(\*\*kwargs)
...................
1248天前 翻译
130#翻译
Returns a new ``QuerySet`` containing objects that do *not* match the given lookup
parameters.
返回一个新的 ``QuerySet`` ,包含不匹配参数kwargs的对象。
1248天前 翻译
131#翻译
order_by(\*fields)
..................
order_by(\*fields)
..................
1248天前 翻译
132#翻译
By default, results returned by a ``QuerySet`` are ordered by the ordering tuple given by
the ``ordering`` option in the models metadata (see Appendix B). You can override this for a
particular query using the ``order_by()`` method:
默认情况下,会返回一个按照models的metadata中的``ordering``选项排序的``QuerySet``(请查看附录B)。你可以调用``order_by()``方法按照一个特定的规则进行排序以覆盖默认的行为:
1178天前 翻译
135#翻译
This result will be ordered by ``pub_date`` descending, then by ``headline`` ascending. The
negative sign in front of ``"-pub_date"`` indicates *descending* order. Ascending order is
assumed if the ``-`` is absent. To order randomly, use ``"?"`` , like so:
结果将先对 ``pub_date`` 进行降序排序,然后对 ``headline`` 进行升序排序。 ``"-pub_date"`` 前面的符号代表降序排序。如果没有 ``"-"`` ,默认为升序排序。要使用随机的顺序,使用 ``"?"`` ,比如:
1159天前 翻译
138#翻译
distinct()
..........
翻译 1482天前 翻译
139#翻译
Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This eliminates
duplicate rows from the query results.
就像使用"SELECT DISTINCT"在SQL查询一样,返回一个新的”QuerySet “。这消除了查询结果中的重复行。
1115天前 翻译
140#翻译
By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this is rarely a
problem, because simple queries such as ``Blog.objects.all()`` dont introduce the
possibility of duplicate result rows.
默认的情况下, "QuerySet"并不能消除重复的行。在练习中,可能会产生问题,因为像 "Blog.objects"这么简单的查询并不一定能产生重复的行。
1135天前 翻译
141#翻译
However, if your query spans multiple tables, its possible to get duplicate results when a
``QuerySet`` is evaluated. Thats when youd use ``distinct()`` .
然而,如果你的查询是多表关联查询,那么``QuerySet``查询的结果可能会有重复数据.因此我们要用``distinct()`` .
1135天前 翻译
142#翻译
values(\*fields)
................
翻译 1482天前 翻译
143#翻译
Returns a special ``QuerySet`` that evaluates to a list of dictionaries instead of
model-instance objects. Each of those dictionaries represents an object, with the keys
corresponding to the attribute names of model objects:
返回一个特殊的QuerySet相当于一个字典列表,而不是model的实例。每个字典代表一个对象,它的keys对应于这个model的属性名。
1115天前 翻译
146#翻译
``values()`` takes optional positional arguments, ``*fields`` , which specify field names to
which the ``SELECT`` should be limited. If you specify the fields, each dictionary will
contain only the field keys/values for the fields you specify. If you dont specify the
fields, each dictionary will contain a key and value for every field in the database table:
``values()`` 方法接受可选的位置参数,, ``*fields`` 参数定义了SELECT中所限定返回的特定字段的名称。如果你指定了这一参数,返回的字典中只会包含你制定的字段的字段名和字段值。如果不指定这个参数的话,返回的字典中会包含数据表中每个字段的字段名和字段值:
889天前 翻译
149#翻译
This method is useful when you know youre only going to need values from a small number of
the available fields and you wont need the functionality of a model instance object. Its
more efficient to select only the fields you need to use.
当你从一小数目的可用字段获取值和不需要一个模型实例对象的时候,这个方法很有用。它的更有效率的领域只选择你需要使用
824天前 翻译
150#翻译
dates(field, kind, order)
.........................
翻译 1482天前 翻译
151#翻译
Returns a special ``QuerySet`` that evaluates to a list of ``datetime.datetime`` objects
representing all available dates of a particular kind within the contents of the
``QuerySet`` .
翻译 1482天前 翻译
152#翻译
The ``field`` argument must be the name of a ``DateField`` or ``DateTimeField`` of your
model. The ``kind`` argument must be either ``"year"`` , ``"month"`` , or ``"day"`` . Each
``datetime.datetime`` object in the result list is truncated to the given ``type`` :
翻译 1482天前 翻译
153#翻译
*   ``"year"`` returns a list of all distinct year values for the field.
翻译 1482天前 翻译
154#翻译
*   ``"month"`` returns a list of all distinct year/month values for the field.
翻译 1482天前 翻译
155#翻译
*   ``"day"`` returns a list of all distinct year/month/day values for the field.
翻译 1482天前 翻译
156#翻译
``order`` , which defaults to ``'ASC'`` , should be either ``'ASC'`` or ``'DESC'`` . This
specifies how to order the results.
翻译 1482天前 翻译
157#翻译
Here are a few examples:
翻译 1482天前 翻译
160#翻译
select_related()
................
翻译 1482天前 翻译
161#翻译
Returns a ``QuerySet`` that will automatically follow foreign key relationships, selecting
that additional related-object data when it executes its query. This is a performance
booster that results in (sometimes much) larger queries but means later use of foreign key
relationships wont require database queries.
翻译 1482天前 翻译
162#翻译
The following examples illustrate the difference between plain lookups and
``select_related()`` lookups. Heres standard lookup:
翻译 1482天前 翻译
165#翻译
And heres ``select_related`` lookup:
一下是select_related()查找
824天前 翻译
168#翻译
``select_related()`` follows foreign keys as far as possible. If you have the following
models:
翻译 1482天前 翻译
171#翻译
then a call to ``Book.objects.select_related().get(id=4)`` will cache the related ``Person``
*and* the related ``City`` :
翻译 212天前 翻译
174#翻译
Note that ``select_related()`` does not follow foreign keys that have ``null=True`` .
翻译 1482天前 翻译
175#翻译
Usually, using ``select_related()`` can vastly improve performance because your application
can avoid many database calls. However, in situations with deeply nested sets of
relationships, ``select_related()`` can sometimes end up following too many relations and
can generate queries so large that they end up being slow.
翻译 1482天前 翻译
176#翻译
extra()
.......
翻译 1482天前 翻译
177#翻译
Sometimes, the Django query syntax by itself cant easily express a complex ``WHERE`` clause.
For these edge cases, Django provides the ``extra()`` ``QuerySet`` modifier a hook for
injecting specific clauses into the SQL generated by a ``QuerySet`` .
翻译 1482天前 翻译
178#翻译
By definition, these extra lookups may not be portable to different database engines
(because youre explicitly writing SQL code) and violate the DRY principle, so you should
avoid them if possible.
翻译 1482天前 翻译
179#翻译
Specify one or more of ``params`` , ``select`` , ``where`` , or ``tables`` . None of the
arguments is required, but you should use at least one of them.
翻译 1482天前 翻译
180#翻译
The ``select`` argument lets you put extra fields in the ``SELECT`` clause. It should be a
dictionary mapping attribute names to SQL clauses to use to calculate that attribute:
翻译 1482天前 翻译
183#翻译
As a result, each ``Entry`` object will have an extra attribute, ``is_recent`` , a Boolean
representing whether the entrys ``pub_date`` is greater than January 1, 2006.
翻译 1482天前 翻译
184#翻译
The next example is more advanced; it does a subquery to give each resulting ``Blog`` object
an ``entry_count`` attribute, an integer count of associated ``Entry`` objects:
翻译 1482天前 翻译
187#翻译
(In this particular case, were exploiting the fact that the query will already contain the
``blog_blog`` table in its ``FROM`` clause.)
翻译 1482天前 翻译
188#翻译
You can define explicit SQL ``WHERE`` clauses perhaps to perform nonexplicit joins by using
``where`` . You can manually add tables to the SQL ``FROM`` clause by using ``tables`` .
翻译 1482天前 翻译
189#翻译
``where`` and ``tables`` both take a list of strings. All ``where`` parameters are ANDed to
any other search criteria:
翻译 1482天前 翻译
192#翻译
The ``select`` and ``where`` parameters described previously may use standard Python
database string placeholders: ``'%s'`` to indicate parameters the database engine should
automatically quote. The ``params`` argument is a list of any extra parameters to be
substituted:
翻译 1482天前 翻译
195#翻译
Always use ``params`` instead of embedding values directly into ``select`` or ``where``
because ``params`` will ensure values are quoted correctly according to your particular
database.
始终用 "params" 而不是在"select" 或"where"中嵌值,因为"param"将按照特定数据库保证values被正确的引用
824天前 翻译
196#翻译
Heres an example of the wrong way:
下面是一个错误的用法
824天前 翻译
199#翻译
Heres an example of the correct way:
下面是一个正确的用法
361天前 翻译
202#翻译
QuerySet Methods That Do Not Return QuerySets
'''''''''''''''''''''''''''''''''''''''''''''
翻译 1482天前 翻译
203#翻译
The following ``QuerySet`` methods evaluate the ``QuerySet`` and return something *otherthan* a ``QuerySet`` a single object, value, and so forth.
翻译 1482天前 翻译
204#翻译
get(\*\*lookup)
...............
翻译 1482天前 翻译
205#翻译
Returns the object matching the given lookup parameters, which should be in the format
described in the Field Lookups section. This raises ``AssertionError`` if more than one
object was found.
返回给定对象匹配的查询参数,应在格式说明在外地查找部分,如果超过一个对象,“AssertionError”异常将被抛出
824天前 翻译
206#翻译
``get()`` raises a ``DoesNotExist`` exception if an object wasnt found for the given
parameters. The ``DoesNotExist`` exception is an attribute of the model class, for example:
翻译 1482天前 翻译
209#翻译
The ``DoesNotExist`` exception inherits from ``django.core.exceptions.ObjectDoesNotExist`` ,
so you can target multiple ``DoesNotExist`` exceptions:
翻译 1482天前 翻译
212#翻译
create(\*\*kwargs)
..................
翻译 1482天前 翻译
213#翻译
This is a convenience method for creating an object and saving it all in one step. It lets
you compress two common steps:
这个快捷的方法可以一次性完成创建并保证对象。它让你完成了下面两个步骤:
1095天前 翻译
216#翻译
into a single line:
翻译 1482天前 翻译
219#翻译
get_or_create(\*\*kwargs)
.........................
翻译 1482天前 翻译
220#翻译
This is a convenience method for looking up an object and creating one if it doesnt exist.
It returns a tuple of ``(object, created)`` , where ``object`` is the retrieved or created
object and ``created`` is a Boolean specifying whether a new object was created.
翻译 1482天前 翻译
221#翻译
This method is meant as a shortcut to boilerplate code and is mostly useful for data-import
scripts, for example:
翻译 1482天前 翻译
224#翻译
This pattern gets quite unwieldy as the number of fields in a model increases. The previous
example can be rewritten using ``get_or_create()`` like so:
翻译 1482天前 翻译
227#翻译
Any keyword arguments passed to ``get_or_create()`` *except* an optional one called
``defaults`` will be used in a ``get()`` call. If an object is found, ``get_or_create()``
returns a tuple of that object and ``False`` . If an object is *not* found,
``get_or_create()`` will instantiate and save a new object, returning a tuple of the new
object and ``True`` . The new object will be created according to this algorithm:
adsf
919天前 翻译
230#翻译
In English, that means start with any non-``'defaults'`` keyword argument that doesnt
contain a double underscore (which would indicate a nonexact lookup). Then add the contents
of ``defaults`` , overriding any keys if necessary, and use the result as the keyword
arguments to the model class.
翻译 1482天前 翻译
231#翻译
If you have a field named ``defaults`` and want to use it as an exact lookup in
``get_or_create()`` , just use ``'defaults__exact'`` like so:
翻译 1482天前 翻译
234#翻译
Note
翻译 1482天前 翻译
235#翻译
As mentioned earlier, ``get_or_create()`` is mostly useful in scripts that need to parse
data and create new records if existing ones arent available. But if you need to use
``get_or_create()`` in a view, please make sure to use it only in ``POST`` requests unless
you have a good reason not to. ``GET`` requests shouldnt have any effect on data; use
``POST`` whenever a request to a page has a side effect on your data.
翻译 1482天前 翻译
236#翻译
count()
.......
翻译 1482天前 翻译
237#翻译
Returns an integer representing the number of objects in the database matching the
``QuerySet`` . ``count()`` never raises exceptions. Heres an example:
翻译 1482天前 翻译
240#翻译
``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should always use
``count()`` rather than loading all of the records into Python objects and calling ``len()``
on the result.
翻译 1482天前 翻译
241#翻译
Depending on which database youre using (e.g., PostgreSQL or MySQL), ``count()`` may return
a long integer instead of a normal Python integer. This is an underlying implementation
quirk that shouldnt pose any real-world problems.
翻译 1482天前 翻译
242#翻译
in_bulk(id_list)
................
翻译 1482天前 翻译
243#翻译
Takes a list of primary key values and returns a dictionary mapping each primary key value
to an instance of the object with the given ID, for example:
翻译 1482天前 翻译
246#翻译
IDs of objects that dont exist are silently dropped from the result dictionary. If you pass
``in_bulk()`` an empty list, youll get an empty dictionary.
翻译 1482天前 翻译
247#翻译
latest(field_name=None)
.......................
翻译 1482天前 翻译
248#翻译
Returns the latest object in the table, by date, using the ``field_name`` provided as the
date field. This example returns the latest ``Entry`` in the table, according to the
``pub_date`` field:
翻译 1482天前 翻译
251#翻译
If your models ``Meta`` specifies ``get_latest_by`` , you can leave off the ``field_name``
argument to ``latest()`` . Django will use the field specified in ``get_latest_by`` by
default.
翻译 1482天前 翻译
252#翻译
Like ``get()`` , ``latest()`` raises ``DoesNotExist`` if an object doesnt exist with the
given parameters.
翻译 1482天前 翻译
253#翻译
Field Lookups
`````````````
翻译 1482天前 翻译
254#翻译
Field lookups are how you specify the meat of an SQL ``WHERE`` clause. Theyre specified as
keyword arguments to the ``QuerySet`` methods ``filter()`` , ``exclude()`` , and ``get()`` .
翻译 1482天前 翻译
255#翻译
Basic lookup keyword arguments take the form ``field__lookuptype=value`` (note the double
underscore). For example:
翻译 1482天前 翻译
258#翻译
translates (roughly) into the following SQL:
翻译 1482天前 翻译
261#翻译
If you pass an invalid keyword argument, a lookup function will raise ``TypeError`` .
翻译 1482天前 翻译
262#翻译
The supported lookup types follow.
翻译 1482天前 翻译
263#翻译
exact
'''''
翻译 1482天前 翻译
264#翻译
Performs an exact match:
翻译 1482天前 翻译
267#翻译
This matches any object with the exact headline Man bites dog.
翻译 1482天前 翻译
268#翻译
If you dont provide a lookup type that is, if your keyword argument doesnt contain a double
underscore the lookup type is assumed to be ``exact`` .
翻译 1482天前 翻译
269#翻译
For example, the following two statements are equivalent:
例如,下面两个语句是等效的:
1035天前 翻译
272#翻译
This is for convenience, because ``exact`` lookups are the common case.
翻译 1482天前 翻译
273#翻译
iexact
''''''
翻译 1482天前 翻译
274#翻译
Performs a case-insensitive exact match:
字符串比较(大小写无关)
1239天前 翻译
277#翻译
This will match ``'Beatles Blog'`` , ``'beatles blog'`` , ``'BeAtLes BLoG'`` , and so forth.
翻译 1482天前 翻译
278#翻译
contains
''''''''
翻译 1482天前 翻译
279#翻译
Performs a case-sensitive containment test:
执行严格区分大小写的内容包含检测:
1156天前 翻译
282#翻译
This will match the headline ``'Today Lennon honored'`` but not ``'today lennon honored'`` .
这将会匹配标题为``'Today Lennon honored'`` 的,而不匹配 ``'today lennon honored'``。
1166天前 翻译
283#翻译
SQLite doesnt support case-sensitive ``LIKE`` statements; when using SQLite,``contains``
acts like ``icontains`` .
SQLite不支持严格区分大小写的 ``LIKE`` 语句,所以在使用SQLite时``contains``的作用和``icontains``一样。
1166天前 翻译
284#翻译
Escaping Percent Signs and Underscores in LIKE Statements
除了LIKE语句中的百分号和下划线
1166天前 翻译
285#翻译
The field lookups that equate to ``LIKE`` SQL statements (``iexact`` , ``contains`` ,
``icontains`` , ``startswith`` , ``istartswith`` , ``endswith`` , and ``iendswith`` ) will
automatically escape the two special characters used in ``LIKE`` statements the percent sign
and the underscore. (In a ``LIKE`` statement, the percent sign signifies a
multiple-character wildcard and the underscore signifies a single-character wildcard.)
使用相当于``LIKE``的SQL查找语句(``iexact`` , ``contains`` , 
``icontains``, ``startswith``, ``istartswith``, ``endswith``, 和``iendswith``)时,会自动的排除``LIKE``语句中使用的两个特殊符号:百分号、下划线。(在一条``LIKE``语句中,百分号是多个字符的通配符,下划线是单个字符的通配符)
1166天前 翻译
286#翻译
This means things should work intuitively, so the abstraction doesnt leak. For example, to
retrieve all the entries that contain a percent sign, just use the percent sign as any other
character:
这意味着使用的直观性,所以不会产生漏提取的。例如,查找所有含有一个百分号的项,只需要想用其他字符一样用一个百分号:
1166天前 翻译
289#翻译
Django takes care of the quoting for you. The resulting SQL will look something like this:
Django 为你处理了这一引用。产生的SQL如下:
1166天前 翻译
292#翻译
The same goes for underscores. Both percentage signs and underscores are handled for you
transparently.
翻译 1482天前 翻译
293#翻译
icontains
'''''''''
翻译 1482天前 翻译
294#翻译
Performs a case-insensitive containment test:
执行一个忽略大小写的内容包含检测:
1156天前 翻译
297#翻译
Unlike ``contains`` , ``icontains`` *will* match ``'today lennon honored'`` .
与``contains``不同, ``icontains`` *会* 匹配 ``'today lennon honored'`` 。
1166天前 翻译
298#翻译
gt, gte, lt, and lte
''''''''''''''''''''
翻译 1482天前 翻译
299#翻译
These represent greater than, greater than or equal to, less than, and less than or equal
to:
这些即大于,大于或等于,小于,小于或等于:
1166天前 翻译
302#翻译
These queries return any object with an ID greater than 4, an ID less than 15, and an ID
greater than or equal to 1, respectively.
这些查询分别返回 ID 大于 4,ID 小于 15,以及 ID 大于等于 0 的对象。
1160天前 翻译
303#翻译
Youll usually use these on numeric fields. Be careful with character fields since character
order isnt always what youd expect (i.e., the string 4 sorts *after* the string 10).
翻译 1482天前 翻译
304#翻译
in
''
翻译 1482天前 翻译
305#翻译
Filters where a value is on a given list:
筛选出包含在给定列表中的数据:
1166天前 翻译
308#翻译
This returns all objects with the ID 1, 3, or 4.
这会返回所有ID为1,3,或4的条目。
1166天前 翻译
309#翻译
startswith
''''''''''
翻译 1482天前 翻译
310#翻译
Performs a case-sensitive starts-with:
区分大小写的开头匹配:
1166天前 翻译
313#翻译
This will return the headlines Will he run? and Willbur named judge, but not Who is Will? or
will found in crypt.
这将返回标题Will he run?和Willbur named judge,但是不会返回Who is Will? 和will found in crypt.
1166天前 翻译
314#翻译
istartswith
'''''''''''
翻译 1482天前 翻译
315#翻译
Performs a case-insensitive starts-with:
翻译 1482天前 翻译
318#翻译
This will return the headlines Will he run?, Willbur named judge, and will found in crypt,
but not Who is Will?
翻译 1482天前 翻译
319#翻译
endswith and iendswith
''''''''''''''''''''''
翻译 1482天前 翻译
320#翻译
Perform case-sensitive and case-insensitive ends-with:
区分大小写和忽略大小写的末尾匹配。
1166天前 翻译
323#翻译
range
'''''
翻译 1482天前 翻译
324#翻译
Performs an inclusive range check:
翻译 1482天前 翻译
327#翻译
You can use ``range`` anywhere you can use ``BETWEEN`` in SQL for dates, numbers, and even
characters.
翻译 1482天前 翻译
328#翻译
year, month, and day
''''''''''''''''''''
翻译 1482天前 翻译
329#翻译
For date/datetime fields, perform exact year, month, or day matches:
对date/datetime类型严格匹配年、月或日:
1166天前 翻译
332#翻译
isnull
''''''
翻译 1482天前 翻译
333#翻译
Takes either ``True`` or ``False`` , which correspond to SQL queries of ``IS NULL`` and ``IS
NOT NULL`` , respectively:
使用``True``或``False``,则分别相当于SQL语句中的``IS NULL``和``IS NOT NULL``:
1166天前 翻译
336#翻译
``__isnull=True`` vs. ``__exact=None``
翻译 1482天前 翻译
337#翻译
There is an important difference between ``__isnull=True`` and ``__exact=None`` .
``__exact=None`` will *always* return an empty result set, because SQL requires that no
value is equal to ``NULL`` . ``__isnull`` determines if the field is currently holding the
value of ``NULL`` without performing a comparison.
``__isnull=True``和``__exact=None``有一个很主要的区别。因为SQL规定无值就等于``NULL`` ,所以``__exact=None``会 *总是* 返回一个空的结果。``__isnull``则取决于该阈是否当前有值 ``NULL``而不进行比较。
1166天前 翻译
338#翻译
search
''''''
翻译 1482天前 翻译
339#翻译
A Boolean full-text search that takes advantage of full-text indexing. This is like
``contains`` but is significantly faster due to full-text indexing.
翻译 1482天前 翻译
340#翻译
Note this is available only in MySQL and requires direct manipulation of the database to add
the full-text index.
翻译 1482天前 翻译
341#翻译
The pk Lookup Shortcut
''''''''''''''''''''''
翻译 1482天前 翻译
342#翻译
For convenience, Django provides a ``pk`` lookup type, which stands for primary_key.
翻译 1482天前 翻译
343#翻译
In the example ``Blog`` model, the primary key is the ``id`` field, so these three
statements are equivalent:
翻译 1482天前 翻译
346#翻译
The use of ``pk`` isnt limited to ``__exact`` queries any query term can be combined with
``pk`` to perform a query on the primary key of a model:
翻译 1482天前 翻译
349#翻译
``pk`` lookups also work across joins. For example, these three statements are equivalent:
翻译 1482天前 翻译
352#翻译
Complex Lookups with Q Objects
``````````````````````````````
使用Q对象做联合查找
``````````````````````````````
1159天前 翻译
353#翻译
Keyword argument queries in ``filter()`` and so on are ANDed together. If you need to
execute more complex queries (e.g., queries with ``OR`` statements), you can use ``Q``
objects.
``filter()``等语句的参数都是取AND运算。如果想要执行更多的联合语句(如``OR``语句),你可以使用 ``Q``对象。
1159天前 翻译
354#翻译
A ``Q`` object (``django.db.models.Q`` ) is an object used to encapsulate a collection of
keyword arguments. These keyword arguments are specified as in the Field Lookups section.
``Q`` 对象 (``django.db.models.Q`` ) 是一个用来囊括参数间连接的对象。这些参数会放在指定的域查询的位置。
1159天前 翻译
355#翻译
For example, this ``Q`` object encapsulates a single ``LIKE`` query:
例如,这个``Q``对象就包括了一个``LIKE``条件:
1159天前 翻译
358#翻译
``Q`` objects can be combined using the ``&`` and ``|`` operators. When an operator is used
on two ``Q`` objects, it yields a new ``Q`` object. For example, this statement yields a
single ``Q`` object that represents the OR of two ``"question__startswith"`` queries:
``Q`` 对象可以用运算符 ``&`` 和 ``|`` 来联合。当一个运算符连接两个 ``Q`` 对象时,就产生了一个新的 ``Q`` 对象。例如,这句生成一个单一的 ``Q`` 对象。相当于两个``"question__startswith"``条件的OR:
1158天前 翻译
361#翻译
This is equivalent to the following SQL ``WHERE`` clause:
这相当于如下的SQL ``WHERE``语句:
1158天前 翻译
364#翻译
You can compose statements of arbitrary complexity by combining ``Q`` objects with the ``&``
and ``|`` operators. You can also use parenthetical grouping.
你可以用运算符``&``和 ``|``连接``Q`` 对象组成任意复杂的语句。你也可以使用附加组。
1158天前 翻译
365#翻译
Each lookup function that takes keyword arguments (e.g., ``filter()`` , ``exclude()`` ,
``get()`` ) can also be passed one or more ``Q`` objects as positional (not-named)
arguments. If you provide multiple ``Q`` object arguments to a lookup function, the
arguments will be ANDed together, for example:
任一带关键字参数的的查找函数(如``filter()`` , ``exclude()`` ,``get()`` )也可将一到多个``Q`` 对象作为参数。如果在一个查询函数中使用多个``Q`` 对象参数,这些参数会被全体做AND运算,例如:
1158天前 翻译
368#翻译
roughly translates into the following SQL:
大致上可转换为如下的SQL:
1158天前 翻译
371#翻译
Lookup functions can mix the use of ``Q`` objects and keyword arguments. All arguments
provided to a lookup function (be they keyword arguments or ``Q`` objects) are ANDed
together. However, if a ``Q`` object is provided, it must precede the definition of any
keyword arguments. For example, the following:
查询函数可以混合使用``Q``对象和关键字作参数。所有的参数作为查询函数的条件(无论他们是关键字参数还是``Q``对象)进行AND运算。然而,如果将一个``Q``对象作为条件,则它必须放在所有关键字参数定义之前。就像下面这样:
1158天前 翻译
374#翻译
would be a valid query, equivalent to the previous example, but this:
这是正确的,就相当于之前的例子。但如果这样:
1158天前 翻译
377#翻译
would not be valid.
就是不正确的。
1158天前 翻译
378#翻译
You can find some examples online at
`http://www.djangoproject.com/documentation/0.96/models/or_lookups/`_.
在互联网上你可以找到一些例子
`http://www.djangoproject.com/documentation/0.96/models/or_lookups/`_.
1158天前 翻译
379#翻译
Related Objects
```````````````
关系对象
````````
1247天前 翻译
380#翻译
When you define a relationship in a model (i.e., a ``ForeignKey`` , ``OneToOneField`` , or
``ManyToManyField`` ), instances of that model will have a convenient API to access the
related object(s).
当你定义了一个关系模型(例如:外键,一对一域,或多对多域),这一模式的实例将有一个方便的API来访问相关的对象。
1135天前 翻译
381#翻译
For example, an ``Entry`` object ``e`` can get its associated ``Blog`` object by accessing
the ``blog`` attribute ``e.blog`` .
例如,Entry对象e能获得相关的blog对象访问博客属性e.blog
1135天前 翻译
382#翻译
Django also creates API accessors for the other side of the relationship the link from the
related model to the model that defines the relationship. For example, a ``Blog`` object
``b`` has access to a list of all related ``Entry`` objects via the ``entry_set`` attribute:
``b.entry_set.all()`` .
翻译 1482天前 翻译
383#翻译
All examples in this section use the sample ``Blog`` , ``Author`` , and ``Entry`` models
defined at the top of this page.
本节将继续使用之前定义的"Blog", "Author", "Entry"模型作为例子
228天前 翻译
384#翻译
Lookups That Span Relationships
'''''''''''''''''''''''''''''''
跨越关系查找
1135天前 翻译
385#翻译
Django offers a powerful and intuitive way to follow relationships in lookups, taking care
of the SQL ``JOIN`` s for you automatically behind the scenes. To span a relationship, just
use the field name of related fields across models, separated by double underscores, until
you get to the field you want.
翻译 1482天前 翻译
386#翻译
This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name`` is ``'Beatles
Blog'`` :
翻译 1482天前 翻译
389#翻译
This spanning can be as deep as youd like.
这跨越可之深可想而知!
1135天前 翻译
390#翻译
It works backward, too. To refer to a reverse relationship, just use the lowercase name of
the model.
翻译 1482天前 翻译
391#翻译
This example retrieves all ``Blog`` objects that have at least one ``Entry`` whose
``headline`` contains ``'Lennon'`` :
翻译 1482天前 翻译
394#翻译
Foreign Key Relationships
'''''''''''''''''''''''''
外键关系
1248天前 翻译
395#翻译
If a model has a ``ForeignKey`` , instances of that model will have access to the related
(foreign) object via a simple attribute of the model, for example:
如果一个模型里面有一个 ``ForeignKey`` 字段,那么它的实例化对象可以很轻易的通过模型的属性来访问与其关联的关系对象,例如:
1240天前 翻译
398#翻译
You can get and set via a foreign key attribute. As you may expect, changes to the foreign
key arent saved to the database until you call ``save()`` , for example:
你可以通过外键属性来获取并设置关联的外键对象。如你所料,单纯修改外键的操作是不能马上将修改的内容同步到数据库中的,你还必须调用 ``save()`` 方法才行,例如:
1240天前 翻译
401#翻译
If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL`` values), you can
assign ``None`` to it:
如果一个 ``ForeignKey`` 字段设置了 ``null=True`` 选项(允许 ``NULL`` 值)时,你可以将 ``None`` 赋给它(译注:但纯设置null=True其实还是不行的,会抛出异常的,还不须把blank=True也设了才行,不知道什么原因,我一直以来都有点怀疑这是个BUG):
1240天前 翻译
404#翻译
Forward access to one-to-many relationships is cached the first time the related object is
accessed. Subsequent accesses to the foreign key on the same object instance are cached, for
example:
翻译 1482天前 翻译
407#翻译
Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates the cache of
all one-to-many relationships ahead of time:
翻译 1482天前 翻译
410#翻译
``select_related()`` is documented in the QuerySet Methods That Return New QuerySets
section.
翻译 1482天前 翻译
411#翻译
Reverse Foreign Key Relationships
'''''''''''''''''''''''''''''''''
外键的反引用关系
1151天前 翻译
412#翻译
Foreign key relationships are automatically symmetrical a reverse relationship is inferred
from the presence of a ``ForeignKey`` pointing to another model.
外键关系是自动对称反引用关系的,这可由一个外键可以指向另一个模型而得知.
1052天前 翻译
413#翻译
If a model has a ``ForeignKey`` , instances of the foreign key model will have access to a
``Manager`` that returns all instances of the first model. By default, this ``Manager`` is
named ``FOO_set`` , where ``FOO`` is the source model name, lowercased. This ``Manager``
returns ``QuerySets`` , which can be filtered and manipulated as described in the Retrieving
Objects section.
如果一个源模型含有一个外键,那么它的外键模型的实例,可以利用"Manager"返回这个源模型的所有实例.默认的这个"Manager"叫做"FOO_set",这个"FOO"是源模型的名字,小写字母,这个"Manager"将返回"QuerySets",对这个QuerySets进行过滤和操作,就像在检索对象章节中介绍的.
1052天前 翻译
414#翻译
Heres an example:
翻译 1482天前 翻译
417#翻译
You can override the ``FOO_set`` name by setting the ``related_name`` parameter in the
``ForeignKey()`` definition. For example, if the ``Entry`` model was altered to ``blog =
ForeignKey(Blog, related_name='entries')`` , the preceding example code would look like
this:
通过在"ForeignKey()"中定义related_name参数,你可以重载"FOO_set"名字.举例,如果把"Entry"模型修改为"blog =ForeignKey(Blog, related_name='entries')",处理例子的代码如下:
1052天前 翻译
420#翻译
You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must be accessed
from an instance:
你不能直接访问这个类的reverse "ForeignKey" "Manager";它必须通过一个实例:
1052天前 翻译
423#翻译
In addition to the ``QuerySet`` methods defined in the Retrieving Objects section, the
``ForeignKey`` ``Manager`` has these additional methods:
翻译 1482天前 翻译
424#翻译
    ``add(obj1, obj2, ...)`` : Adds the specified model objects to the related object set,
    for example:
翻译 1482天前 翻译
427#翻译
    ``create(**kwargs)`` : Creates a new object, saves it, and puts it in the related object
    set. It returns the newly created object:
翻译 1482天前 翻译
430#翻译
    This is equivalent to (but much simpler than) the following:
翻译 1482天前 翻译
433#翻译
    Note that theres no need to specify the keyword argument of the model that defines the
    relationship. In the preceding example, we dont pass the parameter ``blog`` to
    ``create()`` . Django figures out that the new ``Entry`` objects ``blog`` field should
    be set to ``b`` .
注意到,这并没有必要在定义了外键关系的模型中定义关键字参数.在之前的例子中,我们没有传递"blog"参数给"create()".Django会解决这个新建的"Entry"对象的blog字段值设置为b.
1052天前 翻译
434#翻译
    ``remove(obj1, obj2, ...)`` : Removes the specified model objects from the related
    object set:
翻译 1482天前 翻译
437#翻译
    In order to prevent database inconsistency, this method only exists on ``ForeignKey``
    objects where ``null=True`` . If the related field cant be set to ``None`` (``NULL`` ),
    then an object cant be removed from a relation without being added to another. In the
    preceding example, removing ``e`` from ``b.entry_set()`` is equivalent to doing ``e.blog
    = None`` , and because the ``blog`` ``ForeignKey`` doesnt have ``null=True`` , this is
    invalid.
为了阻止数据库的不稳定,这种方法只能对含有外键字段并且该字段可以为null的对象有效,如果关联字段不能设置为"None"("NULL"),then an object can't be removed from a relation without being added to another. 在之前的例子中,从``b.entry_set()`` 中删除e,相当于"e.blog=None",因为这个"blog""ForeignKey"不能"nullTrue",所以这是无效的删除.
1052天前 翻译
438#翻译
    ``clear()`` : Removes all objects from the related object set:
翻译 1482天前 翻译
441#翻译
    Note this doesnt delete the related objects it just disassociates them.
注意: 这并不会删除关联的对象,仅是断开与它们的关联
1052天前 翻译
442#翻译
    Just like ``remove()`` , ``clear()`` is only available on ``ForeignKey``s where
    ``null=True`` .
翻译 1482天前 翻译
443#翻译
To assign the members of a related set in one fell swoop, just assign to it from any
iterable object, for example:
通过给关联集分配一个可迭代的对象可以实现一股脑的把多个对象赋给它
1247天前 翻译
446#翻译
If the ``clear()`` method is available, any pre-existing objects will be removed from the
``entry_set`` before all objects in the iterable (in this case, a list) are added to the
set. If the ``clear()`` method is *not* available, all objects in the iterable will be added
without removing any existing elements.
翻译 1482天前 翻译
447#翻译
Each reverse operation described in this section has an immediate effect on the database.
Every addition, creation, and deletion is immediately and automatically saved to the
database.
翻译 1482天前 翻译
448#翻译
Many-to-Many Relationships
''''''''''''''''''''''''''
多对多关系
''''''''''''''''''''''''''
1247天前 翻译
449#翻译
Both ends of a many-to-many relationship get automatic API access to the other end. The API
works just as a reverse one-to-many relationship (described in the previous section).
在多对多关系的两端,都可以通过相应的API来访问另外的一端。 API的工作方式跟前一节所描述的反向一对多关系差不多。
1247天前 翻译
450#翻译
The only difference is in the attribute naming: the model that defines the
``ManyToManyField`` uses the attribute name of that field itself, whereas the reverse model
uses the lowercased model name of the original model, plus ``'_set'`` (just like reverse
one-to-many relationships).
唯一的不同在于属性的命名:定义了``ManyToManyField``的model的实例使用属性名称本身,另外一端的model的实例则使用model名称的小写加上``_set``来活得关联的对象集(就跟反向一对多关系一样)
1247天前 翻译
451#翻译
An example makes this concept easier to understand:
用例子来说明一下大家会更容易理解:
1247天前 翻译
454#翻译
Like ``ForeignKey`` , ``ManyToManyField`` can specify ``related_name`` . In the preceding
example, if the ``ManyToManyField`` in ``Entry`` had specified ``related_name='entries'`` ,
then each ``Author`` instance would have an ``entries`` attribute instead of ``entry_set`` .
翻译 1482天前 翻译
455#翻译
How Are the Backward Relationships Possible?
翻译 1482天前 翻译
456#翻译
Other object-relational mappers require you to define relationships on both sides. The
Django developers believe this is a violation of the DRY (Dont Repeat Yourself) principle,
so Django requires you to define the relationship on only one end. But how is this possible,
given that a model class doesnt know which other model classes are related to it until those
other model classes are loaded?
翻译 1482天前 翻译
457#翻译
The answer lies in the ``INSTALLED_APPS`` setting. The first time any model is loaded,
Django iterates over every model in ``INSTALLED_APPS`` and creates the backward
relationships in memory as needed. Essentially, one of the functions of ``INSTALLED_APPS``
is to tell Django the entire model domain.
翻译 1482天前 翻译
458#翻译
Queries Over Related Objects
''''''''''''''''''''''''''''
通过关联对象查询
1012天前 翻译
459#翻译
Queries involving related objects follow the same rules as queries involving normal value
fields. When specifying the value for a query to match, you may use either an object
instance itself or the primary key value for the object.
包含关联对象的搜索和包含普通字段的搜索遵循相同的规则。当指定一个值去查询时,你可以使用那个对象的一个实例,也可以使用它的主键值。
1012天前 翻译
460#翻译
For example, if you have a ``Blog`` object ``b`` with ``id=5`` , the following three queries
would be identical:
翻译 1482天前 翻译
463#翻译
Deleting Objects
````````````````
删除对象
````````
1207天前 翻译
464#翻译
The delete method, conveniently, is named ``delete()`` . This method immediately deletes the
object and has no return value:
翻译 1482天前 翻译
467#翻译
You can also delete objects in bulk. Every ``QuerySet`` has a ``delete()`` method, which
deletes all members of that ``QuerySet`` . For example, this deletes all ``Entry`` objects
with a ``pub_date`` year of 2005:
翻译 1482天前 翻译
470#翻译
When Django deletes an object, it emulates the behavior of the SQL constraint ``ON DELETE
CASCADE`` in other words, any objects that had foreign keys pointing at the object to be
deleted will be deleted along with it, for example:
翻译 1482天前 翻译
473#翻译
Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a ``Manager``
itself. This is a safety mechanism to prevent you from accidentally requesting
``Entry.objects.delete()`` and deleting *all* the entries. If you *do* want to delete all
the objects, then you have to explicitly request a complete query set:
翻译 1482天前 翻译
476#翻译
Extra Instance Methods
``````````````````````
翻译 1482天前 翻译
477#翻译
In addition to ``save()`` and ``delete()`` , a model object might get any or all of the
following methods.
翻译 1482天前 翻译
478#翻译
get_FOO_display()
'''''''''''''''''
翻译 1482天前 翻译
479#翻译
For every field that has ``choices`` set, the object will have a ``get_FOO_display()``
method, where ``FOO`` is the name of the field. This method returns the human-readable value
of the field. For example, in the following model:
翻译 1482天前 翻译
482#翻译
each ``Person`` instance will have a ``get_gender_display()`` method:
每一个 ``Person`` 实例都将有一个 ``get_gender_display()`` 方法:
1293天前 翻译
485#翻译
get_next_by_FOO(\*\*kwargs) and get_previous_by_FOO(\*\*kwargs)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
翻译 1482天前 翻译
486#翻译
For every ``DateField`` and ``DateTimeField`` that does not have ``null=True`` , the object
will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()`` methods, where ``FOO`` is the
name of the field. This returns the next and previous object with respect to the date field,
raising the appropriate ``DoesNotExist`` exception when appropriate.
对于任何不允许空值的DateField和DateTimeField字段,将会有"get_next_by_FOO()"和"get_previous_by_FOO()"这两个方法。FOO表示字段名。这两个方法将根据给定的日期字段返回其前一个、后一个对象,适当的时候会抛出"DoesNotExist"的异常。
227天前 翻译
487#翻译
Both methods accept optional keyword arguments, which should be in the format described in
the Field Lookups section.
两种方法都接受可选的关键词参数,这些参数应该遵循 “域查询”一节中的格式。
1207天前 翻译
488#翻译
Note that in the case of identical date values, these methods will use the ID as a fallback
check. This guarantees that no records are skipped or duplicated. For a full example, see
the lookup API samples at `http://www.djangoproject.com/documentation/0.96/models/lookup/`_.
翻译 1482天前 翻译
489#翻译
get_FOO_filename()
''''''''''''''''''
翻译 1482天前 翻译
490#翻译
For every ``FileField`` , the object will have a ``get_FOO_filename()`` method, where
``FOO`` is the name of the field. This returns the full filesystem path to the file,
according to your ``MEDIA_ROOT`` setting.
翻译 1482天前 翻译
491#翻译
Note that ``ImageField`` is technically a subclass of ``FileField`` , so every model with an
``ImageField`` will also get this method.
注意到 ``ImageField``从技术上是 ``FileField``的子类,所以每个有``ImageField``的模型都有这个方法。
1207天前 翻译
492#翻译
get_FOO_url()
'''''''''''''
翻译 1482天前 翻译
493#翻译
For every ``FileField`` , the object will have a ``get_FOO_url()`` method, where ``FOO`` is
the name of the field. This returns the full URL to the file, according to your
``MEDIA_URL`` setting. If the value is blank, this method returns an empty string.
翻译 1482天前 翻译
494#翻译
get_FOO_size()
''''''''''''''
翻译 1482天前 翻译
495#翻译
For every ``FileField`` , the object will have a ``get_FOO_size()`` method, where ``FOO`` is
the name of the field. This returns the size of the file, in bytes. (Behind the scenes, it
uses ``os.path.getsize`` .)
翻译 1024天前 翻译
496#翻译
save_FOO_file(filename, raw_contents)
'''''''''''''''''''''''''''''''''''''
翻译 1482天前 翻译
497#翻译
For every ``FileField`` , the object will have a ``save_FOO_file()`` method, where ``FOO``
is the name of the field. This saves the given file to the filesystem, using the given file
name. If a file with the given file name already exists, Django adds an underscore to the
end of the file name (but before the extension) until the file name is available.
翻译 1482天前 翻译
498#翻译
get_FOO_height() and get_FOO_width()
''''''''''''''''''''''''''''''''''''
翻译 1482天前 翻译
499#翻译
For every ``ImageField`` , the object will have ``get_FOO_height()`` and ``get_FOO_width()``
methods, where ``FOO`` is the name of the field. This returns the height (or width) of the
image, as an integer, in pixels.
翻译 1482天前 翻译
500#翻译
Shortcuts
`````````
捷径
````
1207天前 翻译
501#翻译
As you develop views, you will discover a number of common idioms in the way you use the
database API. Django encodes some of these idioms as shortcuts that can be used to simplify
the process of writing views. These functions are in the ``django.shortcuts`` module.
翻译 1482天前 翻译
502#翻译
get_object_or_404()
'''''''''''''''''''
翻译 1482天前 翻译
503#翻译
One common idiom to use ``get()`` and raise ``Http404`` if the object doesnt exist. This
idiom is captured by ``get_object_or_404()`` . This function takes a Django model as its
first argument and an arbitrary number of keyword arguments, which it passes to the default
managers ``get()`` function. It raises ``Http404`` if the object doesnt exist, for example:
翻译 1482天前 翻译
506#翻译
When you provide a model to this shortcut function, the default manager is used to execute
the underlying ``get()`` query. If you dont want to use the default manager, or if you want
to search a list of related objects, you can provide ``get_object_or_404()`` with a
``Manager`` object instead:
翻译 1482天前 翻译
509#翻译
get_list_or_404()
'''''''''''''''''
翻译 1482天前 翻译
510#翻译
``get_list_or_404`` behaves the same way as ``get_object_or_404()`` , except that it uses
``filter()`` instead of ``get()`` . It raises ``Http404`` if the list is empty.
``get_list_or_404`` 行为与 ``get_object_or_404()`` 相同,但是它用 ``filter()`` 取代了 ``get()`` 。如果列表为空,它将引发 ``Http404`` 。
1247天前 翻译
511#翻译
Falling Back to Raw SQL
```````````````````````
回归原始的SQL操作
`````````````````
1261天前 翻译
512#翻译
If you find yourself needing to write an SQL query that is too complex for Djangos database
mapper to handle, you can fall back into raw SQL statement mode.
如果你需要写一个SQL查询,但是用Django的数据库映射来实现的话太复杂了,那么你可以考虑使用原始的SQL语句。
23天前 翻译
513#翻译
The preferred way to do this is by giving your model custom methods or custom manager
methods that execute queries. Although theres nothing in Django that *requires* database
queries to live in the model layer, this approach keeps all your data access logic in one
place, which is smart from a code organization standpoint. For instructions, see Appendix
B..
解决这个问题的比较好的方法是,给模块写一个自定义的方法或者管理器方法来执行查询。尽管在Django中,数据库查询在模块中没有任何存在的 *必要性* ,但是这种解决方案使你的数据访问在逻辑上保持一致,而且从组织代码的角度讲也更灵活。操作指南见附录B。
1261天前 翻译
514#翻译
Finally, its important to note that the Django database layer is merely an interface to your
database. You can access your database via other tools, programming languages, or database
frameworks theres nothing Django-specific about your database.
最后,请记住Django的数据库层仅仅是访问数据库的一个接口,你可以通过其他的工具、编程语言或者数据库框架来访问数据库,它并不是特定于Django使用的。
1261天前 翻译