“Django/docs/2.2.x/ref/models/fields”的版本间差异

来自菜鸟教程
Django/docs/2.2.x/ref/models/fields
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:模型字段参考 — Django 文档}}
 
<div id="module-django.db.models.fields" class="section">
 
<div id="module-django.db.models.fields" class="section">
  
第4行: 第5行:
 
= 模型字段参考 =
 
= 模型字段参考 =
  
本文档包含 [[#django.db.models.Field|<code>Field</code>]] 类的所有 API 参考,包括 [[#field-options|field options]] 和 [[#field-types|field types]]。
+
本文档包含 [[#django.db.models.Field|Field]] 的所有 API 参考,包括 Django 提供的 [[#field-options|field options]] 和 [[#field-types|field types]]。
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
若内置字段未满足需求,你可以试试 [https://github.com/django/django-localflavor django-localflavor] ([https://django-localflavor.readthedocs.io/ 文档]),它包含了针对各别国家和文件的代码。
+
如果内置字段不起作用,您可以尝试 [https://github.com/django/django-localflavor django-localflavor][https://django-localflavor.readthedocs.io/ documentation]),其中包含对特定国家和文化有用的各种代码。
  
当然,你也可以简单的 [[../../../howto/custom-model-fields|<span class="doc">编写自定义模型字段</span>]]。
+
此外,您可以轻松地 [[../../../howto/custom-model-fields|编写自己的自定义模型字段]] 。
  
  
第18行: 第19行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
技巧性的,这些方法都被定义在 [[#module-django.db.models.fields|<code>django.db.models.fields</code>]],但出于方便的目的,它们被导入 [[../../../topics/db/models#module-django.db|<code>django.db.models</code>]];标准的转换是使用 <code>from django.db import models</code> 并利用 <code>models.&lt;Foo&gt;Field</code> 字段。
+
从技术上讲,这些模型在 [[#module-django.db.models.fields|django.db.models.fields]] 中定义,但为了方便起见,它们被导入到 [[../../../topics/db/models#module-django.db|django.db.models]] 中; 标准约定是使用 <code>from django.db import models</code> 并将字段称为 <code>models.&lt;Foo&gt;Field</code>
  
  
第29行: 第30行:
 
== 字段选项 ==
 
== 字段选项 ==
  
以下参数对所以字段类型均有效,且是可选的。
+
以下参数可用于所有字段类型。 都是可选的。
  
 
<div id="null" class="section">
 
<div id="null" class="section">
  
=== <code>null</code> ===
+
=== null ===
  
; <code>Field.</code><code>null</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">null</span></span>
 
:  
 
:  
  
如果设置为 <code>True</code>, 当该字段为空时,Django 会将数据库中该字段设置为 <code>NULL</code>,默认为 <code>False</code>。
+
如果是 <code>True</code>,Django 将在数据库中将空值存储为 <code>NULL</code>。 默认值为 <code>False</code>。
  
避免在基于字符串的字段(例如 [[#django.db.models.CharField|<code>CharField</code>]] [[#django.db.models.TextField|<code>TextField</code>]])上使用 [[#django.db.models.Field.null|<code>null</code>]]。如果字符串字段的 <code>null=True</code>,那意味着对于“无数据”有两个可能的值:<code>NULL</code> 和空字符串。在大多数情况下,对于“无数据”声明两个值是赘余的,Django 的惯例是使用空字符串而不是 <code>NULL</code>。 一个例外是当 [[#django.db.models.CharField|<code>CharField</code>]] 同时具有 <code>unique=True</code> 和 <code>blank=True</code> 时。 在这种情况下,需要设置 <code>null=True</code>,以便在使用空白值保存多个对象时避免唯一的约束违规。
+
避免在基于字符串的字段上使用 [[#django.db.models.Field.null|null]],例如 [[#django.db.models.CharField|CharField]] [[#django.db.models.TextField|TextField]]。 如果基于字符串的字段具有 <code>null=True</code>,则意味着“无数据”有两个可能的值:<code>NULL</code> 和空字符串。 在大多数情况下,“无数据”有两个可能的值是多余的; Django 约定是使用空字符串,而不是 <code>NULL</code>。 一个例外是 [[#django.db.models.CharField|CharField]] 同时设置了 <code>unique=True</code> 和 <code>blank=True</code>。 在这种情况下,需要 <code>null=True</code> 以避免在保存具有空白值的多个对象时违反唯一约束。
  
For both string-based and non-string-based fields, you will also need to
+
对于基于字符串和非基于字符串的字段,如果您希望在表单中允许空值,您还需要设置 <code>blank=True</code>,因为 [[#django.db.models.Field.null|null]] 参数仅影响数据库存储(见 [[#django.db.models.Field.blank|空白]] )。
set <code>blank=True</code> if you wish to permit empty values in forms, as the
 
[[#django.db.models.Field.null|<code>null</code>]] parameter only affects database storage
 
(see [[#django.db.models.Field.blank|<code>blank</code>]]).
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
When using the Oracle database backend, the value <code>NULL</code> will be stored to
+
当使用 Oracle 数据库后端时,值 <code>NULL</code> 将被存储以表示空字符串,而不管该属性如何。
denote the empty string regardless of this attribute.
 
  
  
第60行: 第57行:
 
<div id="blank" class="section">
 
<div id="blank" class="section">
  
=== <code>blank</code> ===
+
=== blank ===
  
; <code>Field.</code><code>blank</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">blank</span></span>
 
:  
 
:  
  
如果设置为 <code>True</code> ,该字段允许为空。默认为 <code>False</code> 。
+
如果是<code>True</code>,则该字段可以为空。 默认值为 <code>False</code>。
  
Note that this is different than [[#django.db.models.Field.null|<code>null</code>]]. [[#django.db.models.Field.null|<code>null</code>]] is
+
请注意,这与 [[#django.db.models.Field.null|null]] 不同。 [[#django.db.models.Field.null|null]] 纯粹与数据库相关,而 [[#django.db.models.Field.blank|blank]] 与验证相关。 如果字段具有 <code>blank=True</code>,则表单验证将允许输入空值。 如果字段具有 <code>blank=False</code>,则该字段将是必需的。
purely database-related, whereas [[#django.db.models.Field.blank|<code>blank</code>]] is validation-related. If
 
a field has <code>blank=True</code>, form validation will allow entry of an empty value.
 
If a field has <code>blank=False</code>, the field will be required.
 
  
  
第77行: 第71行:
  
 
<span id="field-choices"></span>
 
<span id="field-choices"></span>
=== <code>choices</code> ===
+
=== choices ===
  
; <code>Field.</code><code>choices</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">choices</span></span>
 
:  
 
:  
  
A <span class="xref std std-term">sequence</span> consisting itself of iterables of exactly two items (e.g.
+
一个 <span class="xref std std-term"> 序列 </span> 由恰好两个项目的迭代组成(例如 <code>[(A, B), (A, B) ...]</code>) 用作此字段的选项。 如果给出了选择,则它们由 [[../instances#validating-objects|模型验证]] 强制执行,并且默认表单小部件将是带有这些选择的选择框,而不是标准文本字段。
<code>[(A, B), (A, B) ...]</code>) to use as choices for this field. If choices are
 
given, they're enforced by [[../instances#validating-objects|<span class="std std-ref">model validation</span>]] and the
 
default form widget will be a select box with these choices instead of the
 
standard text field.
 
  
The first element in each tuple is the actual value to be set on the model,
+
每个元组中的第一个元素是要在模型上设置的实际值,第二个元素是人类可读的名称。 例如:
and the second element is the human-readable name. For example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第95行: 第84行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>YEAR_IN_SCHOOL_CHOICES = [
+
<syntaxhighlight lang="python">YEAR_IN_SCHOOL_CHOICES = [
 
     ('FR', 'Freshman'),
 
     ('FR', 'Freshman'),
 
     ('SO', 'Sophomore'),
 
     ('SO', 'Sophomore'),
 
     ('JR', 'Junior'),
 
     ('JR', 'Junior'),
 
     ('SR', 'Senior'),
 
     ('SR', 'Senior'),
]</pre>
+
]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Generally, it's best to define choices inside a model class, and to
+
通常,最好在模型类中定义选择,并为每个值定义一个适当命名的常量:
define a suitably-named constant for each value:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第112行: 第100行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
  
 
class Student(models.Model):
 
class Student(models.Model):
第132行: 第120行:
  
 
     def is_upperclass(self):
 
     def is_upperclass(self):
         return self.year_in_school in (self.JUNIOR, self.SENIOR)</pre>
+
         return self.year_in_school in (self.JUNIOR, self.SENIOR)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Though you can define a choices list outside of a model class and then
+
尽管您可以在模型类之外定义一个选项列表然后引用它,但是在模型类中定义每个选项的选项和名称会保留使用它的类的所有信息,并使选项易于引用(例如,<code>Student.SOPHOMORE</code> 将在导入 <code>Student</code> 模型的任何地方工作)。
refer to it, defining the choices and names for each choice inside the
 
model class keeps all of that information with the class that uses it,
 
and makes the choices easy to reference (e.g, <code>Student.SOPHOMORE</code>
 
will work anywhere that the <code>Student</code> model has been imported).
 
  
You can also collect your available choices into named groups that can
+
您还可以将可用选项收集到可用于组织目的的命名组中:
be used for organizational purposes:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第150行: 第133行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>MEDIA_CHOICES = [
+
<syntaxhighlight lang="python">MEDIA_CHOICES = [
 
     ('Audio', (
 
     ('Audio', (
 
             ('vinyl', 'Vinyl'),
 
             ('vinyl', 'Vinyl'),
第162行: 第145行:
 
     ),
 
     ),
 
     ('unknown', 'Unknown'),
 
     ('unknown', 'Unknown'),
]</pre>
+
]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The first element in each tuple is the name to apply to the group. The
+
每个元组中的第一个元素是应用于组的名称。 第二个元素是一个 2 元组的可迭代对象,每个 2 元组包含一个值和一个人类可读的选项名称。 分组选项可以与单个列表中的未分组选项组合(例如本例中的 unknown 选项)。
second element is an iterable of 2-tuples, with each 2-tuple containing
 
a value and a human-readable name for an option. Grouped options may be
 
combined with ungrouped options within a single list (such as the
 
unknown option in this example).
 
  
For each model field that has [[#django.db.models.Field.choices|<code>choices</code>]] set, Django will add a
+
对于每个设置了 [[#django.db.models.Field.choices|choices]] 的模型字段,Django 将添加一个方法来检索字段当前值的可读名称。 请参阅数据库 API 文档中的 [[../instances#django.db.models.Model|get_FOO_display()]]
method to retrieve the human-readable name for the field's current value. See
 
[[../instances#django.db.models.Model|<code>get_FOO_display()</code>]] in the database API
 
documentation.
 
  
Note that choices can be any sequence object -- not necessarily a list or
+
请注意,选择可以是任何序列对象——不一定是列表或元组。 这使您可以动态构建选择。 但是,如果您发现自己将 [[#django.db.models.Field.choices|choices]] 修改为动态,则最好使用带有 [[#django.db.models.ForeignKey|ForeignKey]] 的适当数据库表。 [[#django.db.models.Field.choices|choices]] 用于不会发生太大变化的静态数据,如果有的话。
tuple. This lets you construct choices dynamically. But if you find yourself
 
hacking [[#django.db.models.Field.choices|<code>choices</code>]] to be dynamic, you're probably better off using
 
a proper database table with a [[#django.db.models.ForeignKey|<code>ForeignKey</code>]]. [[#django.db.models.Field.choices|<code>choices</code>]] is
 
meant for static data that doesn't change much, if ever.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
每当 <code>choices</code> 的顺序变动时将会创建新的迁移。
+
每次 <code>choices</code> 的顺序更改时,都会创建一个新的迁移。
  
  
 
</div>
 
</div>
Unless [[#django.db.models.Field.blank|<code>blank=False</code>]] is set on the field along with a
+
除非 [[#django.db.models.Field.blank|blank=False]] [[#django.db.models.Field.default|default]] 一起在字段上设置,那么包含 <code>&quot;---------&quot;</code> 的标签将与选择框一起呈现。 要覆盖此行为,请向包含 <code>None</code> <code>choices</code> 添加一个元组; 例如 <code>(None, 'Your String For Display')</code>。 或者,您可以使用空字符串而不是 <code>None</code> ,这是有意义的 - 例如在 [[#django.db.models.CharField|CharField]] 上。
[[#django.db.models.Field.default|<code>default</code>]] then a label containing <code>&quot;---------&quot;</code> will be rendered
 
with the select box. To override this behavior, add a tuple to <code>choices</code>
 
containing <code>None</code>; e.g. <code>(None, 'Your String For Display')</code>.
 
Alternatively, you can use an empty string instead of <code>None</code> where this makes
 
sense - such as on a [[#django.db.models.CharField|<code>CharField</code>]].
 
  
  
第203行: 第170行:
 
<div id="db-column" class="section">
 
<div id="db-column" class="section">
  
=== <code>db_column</code> ===
+
=== db_column ===
  
; <code>Field.</code><code>db_column</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">db_column</span></span>
 
:  
 
:  
  
The name of the database column to use for this field. If this isn't given,
+
用于此字段的数据库列的名称。 如果没有给出,Django 将使用该字段的名称。
Django will use the field's name.
 
  
If your database column name is an SQL reserved word, or contains
+
如果您的数据库列名称是 SQL 保留字,或者包含 Python 变量名称中不允许的字符(尤其是连字符),那也没关系。 Django 在幕后引用列名和表名。
characters that aren't allowed in Python variable names -- notably, the
 
hyphen -- that's OK. Django quotes column and table names behind the
 
scenes.
 
  
  
第220行: 第183行:
 
<div id="db-index" class="section">
 
<div id="db-index" class="section">
  
=== <code>db_index</code> ===
+
=== db_index ===
  
; <code>Field.</code><code>db_index</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">db_index</span></span>
 
:  
 
:  
  
If <code>True</code>, a database index will be created for this field.
+
如果是 <code>True</code>,将为此字段创建数据库索引。
  
  
第231行: 第194行:
 
<div id="db-tablespace" class="section">
 
<div id="db-tablespace" class="section">
  
=== <code>db_tablespace</code> ===
+
=== db_tablespace ===
  
; <code>Field.</code><code>db_tablespace</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">db_tablespace</span></span>
 
:  
 
:  
  
The name of the [[../../../topics/db/tablespaces|<span class="doc">database tablespace</span>]] to use for
+
用于该字段索引的 [[../../../topics/db/tablespaces|数据库表空间]] 的名称(如果该字段已编入索引)。 默认是项目的 [[#id1|:setting:`DEFAULT_INDEX_TABLESPACE`]] 设置(如果已设置)或模型的 [[../options#django.db.models.Options|db_tablespace]](如果有)。 如果后端不支持索引表空间,则忽略此选项。
this field's index, if this field is indexed. The default is the project's
 
[[../../settings#std-setting-DEFAULT_INDEX_TABLESPACE|<code>DEFAULT_INDEX_TABLESPACE</code>]] setting, if set, or the
 
[[../options#django.db.models.Options|<code>db_tablespace</code>]] of the model, if any. If the backend doesn't
 
support tablespaces for indexes, this option is ignored.
 
  
  
第246行: 第205行:
 
<div id="default" class="section">
 
<div id="default" class="section">
  
=== <code>default</code> ===
+
=== default ===
  
; <code>Field.</code><code>default</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">default</span></span>
 
:  
 
:  
  
该字段的默认值。可以是一个值或者是个可调用的对象,如果是个可调用对象,每次实例化模型时都会调用该对象。
+
字段的默认值。 这可以是值或可调用对象。 如果可调用,则每次创建新对象时都会调用它。
  
The default can't be a mutable object (model instance, <code>list</code>, <code>set</code>, etc.),
+
默认值不能是可变对象(模型实例、<code>list</code><code>set</code> 等),因为对该对象的同一实例的引用将用作所有对象的默认值新模型实例。 相反,将所需的默认值包装在一个可调用对象中。 例如,如果要为 [[../../contrib/postgres/fields#django.contrib.postgres.fields|JSONField]] 指定默认的 <code>dict</code>,请使用函数:
as a reference to the same instance of that object would be used as the default
 
value in all new model instances. Instead, wrap the desired default in a
 
callable. For example, if you want to specify a default <code>dict</code> for
 
[[../../contrib/postgres/fields#django.contrib.postgres.fields|<code>JSONField</code>]], use a function:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第263行: 第218行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def contact_default():
+
<syntaxhighlight lang="python">def contact_default():
     return {&quot;email&quot;: &quot;to1@example.com&quot;}
+
     return {"email": "to1@example.com"}
  
contact_info = JSONField(&quot;ContactInfo&quot;, default=contact_default)</pre>
+
contact_info = JSONField("ContactInfo", default=contact_default)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>lambda</code>s can't be used for field options like <code>default</code> because they
+
<code>lambda</code>s 不能用于像 <code>default</code> 这样的字段选项,因为它们不能被迁移 [[../../../topics/migrations#migration-serializing|序列化]] 。 有关其他注意事项,请参阅该文档。
can't be [[../../../topics/migrations#migration-serializing|<span class="std std-ref">serialized by migrations</span>]]. See that
 
documentation for other caveats.
 
  
For fields like [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] that map to model instances, defaults
+
对于像 [[#django.db.models.ForeignKey|ForeignKey]] 这样映射到模型实例的字段,默认值应该是它们引用的字段的值(<code>pk</code>,除非设置了 [[#django.db.models.ForeignKey.to_field|to_field]])而不是模型实例。
should be the value of the field they reference (<code>pk</code> unless
 
[[#django.db.models.ForeignKey.to_field|<code>to_field</code>]] is set) instead of model instances.
 
  
The default value is used when new model instances are created and a value
+
在创建新模型实例并且未为该字段提供值时使用默认值。 当字段为主键时,字段设置为<code>None</code>时也使用默认值。
isn't provided for the field. When the field is a primary key, the default is
 
also used when the field is set to <code>None</code>.
 
  
  
第287行: 第236行:
 
<div id="editable" class="section">
 
<div id="editable" class="section">
  
=== <code>editable</code> ===
+
=== editable ===
  
; <code>Field.</code><code>editable</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">editable</span></span>
 
:  
 
:  
  
If <code>False</code>, the field will not be displayed in the admin or any other
+
如果是 <code>False</code>,该字段将不会显示在 admin 或任何其他 [[../../../topics/forms/modelforms#django.forms|ModelForm]] 中。 在 [[../instances#validating-objects|模型验证]] 期间也会跳过它们。 默认值为 <code>True</code>
[[../../../topics/forms/modelforms#django.forms|<code>ModelForm</code>]]. They are also skipped during [[../instances#validating-objects|<span class="std std-ref">model
 
validation</span>]]. Default is <code>True</code>.
 
  
  
第300行: 第247行:
 
<div id="error-messages" class="section">
 
<div id="error-messages" class="section">
  
=== <code>error_messages</code> ===
+
=== error_messages ===
  
; <code>Field.</code><code>error_messages</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">error_messages</span></span>
 
:  
 
:  
  
The <code>error_messages</code> argument lets you override the default messages that the
+
<code>error_messages</code> 参数允许您覆盖该字段将引发的默认消息。 传入一个字典,其键与要覆盖的错误消息匹配。
field will raise. Pass in a dictionary with keys matching the error messages you
 
want to override.
 
  
Error message keys include <code>null</code>, <code>blank</code>, <code>invalid</code>, <code>invalid_choice</code>,
+
错误信息键包括 <code>null</code><code>blank</code><code>invalid</code><code>invalid_choice</code><code>unique</code> <code>unique_for_date</code>。 在下面的 [[#field-types|字段类型]] 部分中为每个字段指定了其他错误消息键。
<code>unique</code>, and <code>unique_for_date</code>. Additional error message keys are
 
specified for each field in the [[#field-types|Field types]] section below.
 
  
These error messages often don't propagate to forms. See
+
这些错误消息通常不会传播到表单。 请参阅 [[../../../topics/forms/modelforms#considerations-regarding-model-errormessages|关于模型的 error_messages]] 的注意事项。
[[../../../topics/forms/modelforms#considerations-regarding-model-errormessages|<span class="std std-ref">有关模型的 error_messages 的注意事项</span>]].
 
  
  
第320行: 第262行:
 
<div id="help-text" class="section">
 
<div id="help-text" class="section">
  
=== <code>help_text</code> ===
+
=== help_text ===
  
; <code>Field.</code><code>help_text</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">help_text</span></span>
 
:  
 
:  
  
额外的“帮助”文本,随表单控件一同显示。即便你的字段未用于表单,它对于生成文档也是很有用的。
+
与表单小部件一起显示的额外“帮助”文本。 即使您的字段未在表单上使用,它也可用于文档。
  
Note that this value is ''not'' HTML-escaped in automatically-generated
+
请注意,此值在自动生成的表单中是 ''而非'' HTML 转义。 如果您愿意,这允许您在 [[#django.db.models.Field.help_text|help_text]] 中包含 HTML。 例如:
forms. This lets you include HTML in [[#django.db.models.Field.help_text|<code>help_text</code>]] if you so
 
desire. For example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第335行: 第275行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>help_text=&quot;Please use the following format: &lt;em&gt;YYYY-MM-DD&lt;/em&gt;.&quot;</pre>
+
<syntaxhighlight lang="python">help_text="Please use the following format: <em>YYYY-MM-DD</em>."</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Alternatively you can use plain text and
+
或者,您可以使用纯文本和 [[../../utils#django.utils.html|django.utils.html.escape()]] 来转义任何 HTML 特殊字符。 确保您对可能来自不受信任用户的任何帮助文本进行转义以避免跨站点脚本攻击。
[[../../utils#django.utils.html|<code>django.utils.html.escape()</code>]] to escape any HTML special characters. Ensure
 
that you escape any help text that may come from untrusted users to avoid a
 
cross-site scripting attack.
 
  
  
第349行: 第286行:
 
<div id="primary-key" class="section">
 
<div id="primary-key" class="section">
  
=== <code>primary_key</code> ===
+
=== primary_key ===
  
; <code>Field.</code><code>primary_key</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">primary_key</span></span>
 
:  
 
:  
  
如果设置为 <code>True</code> ,将该字段设置为该模型的主键。
+
如果是 <code>True</code>,则该字段是模型的主键。
  
If you don't specify <code>primary_key=True</code> for any field in your model, Django
+
如果你的模型中没有为任何字段指定 <code>primary_key=True</code>,Django 会自动添加一个 [[#django.db.models.AutoField|AutoField]] 来保存主键,所以你不需要设置 <code>primary_key=True</code> ] 在您的任何字段上,除非您想覆盖默认的主键行为。 有关更多信息,请参阅 [[../../../topics/db/models#automatic-primary-key-fields|自动主键字段]]
will automatically add an [[#django.db.models.AutoField|<code>AutoField</code>]] to hold the primary key, so you
 
don't need to set <code>primary_key=True</code> on any of your fields unless you want to
 
override the default primary-key behavior. For more, see
 
[[../../../topics/db/models#automatic-primary-key-fields|<span class="std std-ref">自动设置主键</span>]].
 
  
<code>primary_key=True</code> implies [[#django.db.models.Field.null|<code>null=False</code>]] and
+
<code>primary_key=True</code> 意味着 [[#django.db.models.Field.null|null=False]] [[#django.db.models.Field.unique|unique=True]]。 一个对象上只允许有一个主键。
[[#django.db.models.Field.unique|<code>unique=True</code>]]. Only one primary key is allowed on an
 
object.
 
  
The primary key field is read-only. If you change the value of the primary
+
主键字段是只读的。 如果您在现有对象上更改主键的值然后保存它,则会在旧对象旁边创建一个新对象。
key on an existing object and then save it, a new object will be created
 
alongside the old one.
 
  
  
第374行: 第303行:
 
<div id="unique" class="section">
 
<div id="unique" class="section">
  
=== <code>unique</code> ===
+
=== unique ===
  
; <code>Field.</code><code>unique</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">unique</span></span>
 
:  
 
:  
  
如果设置为 <code>True</code>,这个字段必须在整个表中保持值唯一。
+
如果是 <code>True</code>,则该字段在整个表中必须是唯一的。
  
This is enforced at the database level and by model validation. If
+
这是在数据库级别和模型验证中强制执行的。 如果您尝试在 [[#django.db.models.Field.unique|unique]] 字段中保存具有重复值的模型,模型的 [[../instances#django.db.models.Model|save()]] 方法将引发 [[../../exceptions#django.db|django.db.IntegrityError]] .
you try to save a model with a duplicate value in a [[#django.db.models.Field.unique|<code>unique</code>]]
 
field, a [[../../exceptions#django.db|<code>django.db.IntegrityError</code>]] will be raised by the model's
 
[[../instances#django.db.models.Model|<code>save()</code>]] method.
 
  
This option is valid on all field types except [[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]] and
+
此选项对除 [[#django.db.models.ManyToManyField|ManyToManyField]] [[#django.db.models.OneToOneField|OneToOneField]] 之外的所有字段类型都有效。
[[#django.db.models.OneToOneField|<code>OneToOneField</code>]].
 
  
Note that when <code>unique</code> is <code>True</code>, you don't need to specify
+
注意,当 <code>unique</code> <code>True</code> 时,不需要指定 [[#django.db.models.Field.db_index|db_index]],因为 <code>unique</code> 意味着创建索引。
[[#django.db.models.Field.db_index|<code>db_index</code>]], because <code>unique</code> implies the creation of an index.
 
  
  
第396行: 第320行:
 
<div id="unique-for-date" class="section">
 
<div id="unique-for-date" class="section">
  
=== <code>unique_for_date</code> ===
+
=== unique_for_date ===
  
; <code>Field.</code><code>unique_for_date</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">unique_for_date</span></span>
 
:  
 
:  
  
Set this to the name of a [[#django.db.models.DateField|<code>DateField</code>]] or [[#django.db.models.DateTimeField|<code>DateTimeField</code>]] to
+
将此设置为 [[#django.db.models.DateField|DateField]] [[#django.db.models.DateTimeField|DateTimeField]] 的名称,以要求此字段对于日期字段的值是唯一的。
require that this field be unique for the value of the date field.
 
  
For example, if you have a field <code>title</code> that has
+
例如,如果您有一个字段 <code>title</code> 具有 <code>unique_for_date=&quot;pub_date&quot;</code>,那么 Django 将不允许输入具有相同 <code>title</code> <code>pub_date</code> 的两条记录.
<code>unique_for_date=&quot;pub_date&quot;</code>, then Django wouldn't allow the entry of two
 
records with the same <code>title</code> and <code>pub_date</code>.
 
  
Note that if you set this to point to a [[#django.db.models.DateTimeField|<code>DateTimeField</code>]], only the date
+
请注意,如果您将其设置为指向 [[#django.db.models.DateTimeField|DateTimeField]],则只会考虑该字段的日期部分。 此外,当 [[#id3|:setting:`USE_TZ`]] <code>True</code> 时,将在对象保存时的 [[../../../topics/i18n/timezones#default-current-time-zone|当前时区]] 中进行检查。
portion of the field will be considered. Besides, when [[../../settings#std-setting-USE_TZ|<code>USE_TZ</code>]] is
 
<code>True</code>, the check will be performed in the [[../../../topics/i18n/timezones#default-current-time-zone|<span class="std std-ref">current time zone</span>]] at the time the object gets saved.
 
  
This is enforced by [[../instances#django.db.models.Model|<code>Model.validate_unique()</code>]] during model validation
+
这是在模型验证期间由 [[../instances#django.db.models.Model|Model.validate_unique()]] 强制执行的,但不是在数据库级别执行的。 如果任何 [[#django.db.models.Field.unique_for_date|unique_for_date]] 约束涉及不属于 [[../../../topics/forms/modelforms#django.forms|ModelForm]] 的字段(例如,如果其中一个字段在 <code>exclude</code> 中列出或具有 [[#django.db.models.Field.editable|editable= False]]), [[../instances#django.db.models.Model|Model.validate_unique()]] 将跳过对该特定约束的验证。
but not at the database level. If any [[#django.db.models.Field.unique_for_date|<code>unique_for_date</code>]] constraint
 
involves fields that are not part of a [[../../../topics/forms/modelforms#django.forms|<code>ModelForm</code>]] (for
 
example, if one of the fields is listed in <code>exclude</code> or has
 
[[#django.db.models.Field.editable|<code>editable=False</code>]]), [[../instances#django.db.models.Model|<code>Model.validate_unique()</code>]] will
 
skip validation for that particular constraint.
 
  
  
第423行: 第337行:
 
<div id="unique-for-month" class="section">
 
<div id="unique-for-month" class="section">
  
=== <code>unique_for_month</code> ===
+
=== unique_for_month ===
  
; <code>Field.</code><code>unique_for_month</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">unique_for_month</span></span>
 
:  
 
:  
  
Like [[#django.db.models.Field.unique_for_date|<code>unique_for_date</code>]], but requires the field to be unique with
+
[[#django.db.models.Field.unique_for_date|unique_for_date]] 类似,但要求该字段相对于月份而言是唯一的。
respect to the month.
 
  
  
第435行: 第348行:
 
<div id="unique-for-year" class="section">
 
<div id="unique-for-year" class="section">
  
=== <code>unique_for_year</code> ===
+
=== unique_for_year ===
  
; <code>Field.</code><code>unique_for_year</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">unique_for_year</span></span>
 
:  
 
:  
  
Like [[#django.db.models.Field.unique_for_date|<code>unique_for_date</code>]] and [[#django.db.models.Field.unique_for_month|<code>unique_for_month</code>]].
+
[[#django.db.models.Field.unique_for_date|unique_for_date]] [[#django.db.models.Field.unique_for_month|unique_for_month]]
  
  
第446行: 第359行:
 
<div id="verbose-name" class="section">
 
<div id="verbose-name" class="section">
  
=== <code>verbose_name</code> ===
+
=== verbose_name ===
  
; <code>Field.</code><code>verbose_name</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">verbose_name</span></span>
 
:  
 
:  
  
A human-readable name for the field. If the verbose name isn't given, Django
+
字段的可读名称。 如果没有给出详细名称,Django 将使用字段的属性名称自动创建它,将下划线转换为空格。 请参阅 [[../../../topics/db/models#verbose-field-names|详细字段名称]]
will automatically create it using the field's attribute name, converting
 
underscores to spaces. See [[../../../topics/db/models#verbose-field-names|<span class="std std-ref">Verbose field names</span>]].
 
  
  
第459行: 第370行:
 
<div id="validators" class="section">
 
<div id="validators" class="section">
  
=== <code>validators</code> ===
+
=== validators ===
  
; <code>Field.</code><code>validators</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">validators</span></span>
 
:  
 
:  
  
A list of validators to run for this field. See the [[../../validators|<span class="doc">validators
+
要为此字段运行的验证器列表。 有关更多信息,请参阅 [[../../validators|验证器文档]]
documentation</span>]] for more information.
 
  
 
<div id="registering-and-fetching-lookups" class="section">
 
<div id="registering-and-fetching-lookups" class="section">
  
==== Registering and fetching lookups ====
+
==== 注册和获取查询 ====
  
<code>Field</code> implements the [[../lookups#lookup-registration-api|<span class="std std-ref">lookup registration API</span>]].
+
<code>Field</code> 实现了 [[../lookups#lookup-registration-api|查找注册 API]]API 可用于自定义字段类可用的查找,以及如何从字段中获取查找。
The API can be used to customize which lookups are available for a field class, and
 
how lookups are fetched from a field.
 
  
  
第488行: 第396行:
 
<div id="autofield" class="section">
 
<div id="autofield" class="section">
  
=== <code>AutoField</code> ===
+
=== AutoField ===
  
; ''class'' <code>AutoField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#AutoField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">AutoField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
An [[#django.db.models.IntegerField|<code>IntegerField</code>]] that automatically increments
+
[[#django.db.models.IntegerField|IntegerField]] 根据可用 ID 自动递增。 您通常不需要直接使用它; 如果您没有另外指定,主键字段将自动添加到您的模型中。 请参阅 [[../../../topics/db/models#automatic-primary-key-fields|自动主键字段]]
according to available IDs. You usually won't need to use this directly; a
 
primary key field will automatically be added to your model if you don't specify
 
otherwise. See [[../../../topics/db/models#automatic-primary-key-fields|<span class="std std-ref">自动设置主键</span>]].
 
  
  
第502行: 第407行:
 
<div id="bigautofield" class="section">
 
<div id="bigautofield" class="section">
  
=== <code>BigAutoField</code> ===
+
=== BigAutoField ===
  
; ''class'' <code>BigAutoField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#BigAutoField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">BigAutoField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A 64-bit integer, much like an [[#django.db.models.AutoField|<code>AutoField</code>]] except that it is
+
一个 64 位整数,很像 [[#django.db.models.AutoField|AutoField]],除了它保证适合从 <code>1</code> <code>9223372036854775807</code> 的数字。
guaranteed to fit numbers from <code>1</code> to <code>9223372036854775807</code>.
 
  
  
第514行: 第418行:
 
<div id="bigintegerfield" class="section">
 
<div id="bigintegerfield" class="section">
  
=== <code>BigIntegerField</code> ===
+
=== BigIntegerField ===
  
; ''class'' <code>BigIntegerField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#BigIntegerField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">BigIntegerField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A 64-bit integer, much like an [[#django.db.models.IntegerField|<code>IntegerField</code>]] except that it is
+
一个 64 位整数,很像 [[#django.db.models.IntegerField|IntegerField]],除了它保证适合从 <code>-9223372036854775808</code> <code>9223372036854775807</code> 的数字。 此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]
guaranteed to fit numbers from <code>-9223372036854775808</code> to
 
<code>9223372036854775807</code>. The default form widget for this field is a
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]].
 
  
  
第528行: 第429行:
 
<div id="binaryfield" class="section">
 
<div id="binaryfield" class="section">
  
=== <code>BinaryField</code> ===
+
=== BinaryField ===
  
; ''class'' <code>BinaryField</code><span class="sig-paren">(</span>''<span class="n">max_length</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#BinaryField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">BinaryField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A field to store raw binary data. It can be assigned <code>bytes</code>,
+
存储原始二进制数据的字段。 可以分配 <code>bytes</code><code>bytearray</code> <code>memoryview</code>
<code>bytearray</code>, or <code>memoryview</code>.
 
  
By default, <code>BinaryField</code> sets [[#django.db.models.Field.editable|<code>editable</code>]] to <code>False</code>, in which
+
默认情况下,<code>BinaryField</code> [[#django.db.models.Field.editable|editable]] 设置为 <code>False</code>,在这种情况下,它不能包含在 [[../../../topics/forms/modelforms#django.forms|ModelForm]] 中。
case it can't be included in a [[../../../topics/forms/modelforms#django.forms|<code>ModelForm</code>]].
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
Older versions don't allow setting <code>editable</code> to <code>True</code>.
+
<span class="versionmodified changed"> 2.1 版本变更: </span> 旧版本不允许将 <code>editable</code> 设置为 <code>True</code>
  
  
 
</div>
 
</div>
<code>BinaryField</code> has one extra optional argument:
+
<code>BinaryField</code> 有一个额外的可选参数:
  
; <code>BinaryField.</code><code>max_length</code>
+
; <span class="sig-prename descclassname"><span class="pre">BinaryField.</span></span><span class="sig-name descname"><span class="pre">max_length</span></span>
: The maximum length (in characters) of the field. The maximum length is enforced in Django's validation using [[../../validators#django.core.validators|<code>MaxLengthValidator</code>]].
+
: 字段的最大长度(以字符为单位)。 最大长度在 Django 的验证中使用 [[../../validators#django.core.validators|MaxLengthValidator]] 强制执行。
  
 
<div class="admonition-abusing-binaryfield admonition">
 
<div class="admonition-abusing-binaryfield admonition">
  
Abusing <code>BinaryField</code>
+
滥用 <code>BinaryField</code>
  
Although you might think about storing files in the database, consider that
+
尽管您可能会考虑将文件存储在数据库中,但请考虑在 99% of 的情况下这是糟糕的设计。 该字段是 ''不是'' 替代正确的 [[../../../howto/static-files/index|静态文件]] 处理。
it is bad design in 99% of the cases. This field is ''not'' a replacement for
 
proper [[../../../howto/static-files/index|<span class="doc">static files</span>]] handling.
 
  
  
第564行: 第461行:
 
<div id="booleanfield" class="section">
 
<div id="booleanfield" class="section">
  
=== <code>BooleanField</code> ===
+
=== BooleanField ===
  
; ''class'' <code>BooleanField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#BooleanField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">BooleanField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A true/false field.
+
一个 true/false 字段。
  
The default form widget for this field is [[../../forms/widgets#django.forms|<code>CheckboxInput</code>]],
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|CheckboxInput]],或 [[../../forms/widgets#django.forms|NullBooleanSelect]] 如果 [[#django.db.models.Field.null|null=True]]
or [[../../forms/widgets#django.forms|<code>NullBooleanSelect</code>]] if [[#django.db.models.Field.null|<code>null=True</code>]].
 
  
The default value of <code>BooleanField</code> is <code>None</code> when [[#django.db.models.Field.default|<code>Field.default</code>]]
+
[[#django.db.models.Field.default|Field.default]] 未定义时,<code>BooleanField</code> 的默认值为 <code>None</code>
isn't defined.
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
In older versions, this field doesn't permit <code>null=True</code>, so you have to
+
<span class="versionmodified changed"> 2.1 版本变更: </span> 在旧版本中,此字段不允许 <code>null=True</code>,因此您必须使用 [[#django.db.models.NullBooleanField|NullBooleanField]] 代替。 现在不鼓励使用后者,因为它可能会在未来版本的 Django 中被弃用。
use [[#django.db.models.NullBooleanField|<code>NullBooleanField</code>]] instead. Using the latter is now discouraged
 
as it's likely to be deprecated in a future version of Django.
 
  
In older versions, this field has [[#django.db.models.Field.blank|<code>blank=True</code>]]
+
在旧版本中,此字段隐式具有 [[#django.db.models.Field.blank|blank=True]]。 您可以通过设置 <code>blank=True</code> 来恢复之前的行为。
implicitly. You can restore the previous behavior by setting
 
<code>blank=True</code>.
 
  
  
第593行: 第484行:
 
<div id="charfield" class="section">
 
<div id="charfield" class="section">
  
=== <code>CharField</code> ===
+
=== CharField ===
  
; ''class'' <code>CharField</code><span class="sig-paren">(</span>''<span class="n">max_length</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#CharField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">CharField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A string field, for small- to large-sized strings.
+
一个字符串字段,适用于小到大的字符串。
  
For large amounts of text, use [[#django.db.models.TextField|<code>TextField</code>]].
+
对于大量文本,请使用 [[#django.db.models.TextField|TextField]]
  
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>TextInput</code>]].
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]
  
[[#django.db.models.CharField|<code>CharField</code>]] has one extra required argument:
+
[[#django.db.models.CharField|CharField]] 有一个额外的必需参数:
  
; <code>CharField.</code><code>max_length</code>
+
; <span class="sig-prename descclassname"><span class="pre">CharField.</span></span><span class="sig-name descname"><span class="pre">max_length</span></span>
: The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using [[../../validators#django.core.validators|<code>MaxLengthValidator</code>]].
+
: 字段的最大长度(以字符为单位)。 max_length 在数据库级别和 Django 的验证中使用 [[../../validators#django.core.validators|MaxLengthValidator]] 强制执行。
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
If you are writing an application that must be portable to multiple
+
如果您正在编写一个必须可移植到多个数据库后端的应用程序,您应该注意某些后端对 <code>max_length</code> 的限制。 详情请参考[[../../databases|数据库后端笔记]]
database backends, you should be aware that there are restrictions on
 
<code>max_length</code> for some backends. Refer to the [[../../databases|<span class="doc">database backend
 
notes</span>]] for details.
 
  
  
第624行: 第512行:
 
<div id="datefield" class="section">
 
<div id="datefield" class="section">
  
=== <code>DateField</code> ===
+
=== DateField ===
  
; ''class'' <code>DateField</code><span class="sig-paren">(</span>''<span class="n">auto_now</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">auto_now_add</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#DateField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">DateField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">auto_now</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">auto_now_add</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A date, represented in Python by a <code>datetime.date</code> instance. Has a few extra,
+
一个日期,在 Python 中由 <code>datetime.date</code> 实例表示。 有一些额外的可选参数:
optional arguments:
 
  
 
<dl>
 
<dl>
<dt><code>DateField.</code><code>auto_now</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">DateField.</span></span><span class="sig-name descname"><span class="pre">auto_now</span></span></dt>
<dd><p>Automatically set the field to now every time the object is saved. Useful
+
<dd><p>每次保存对象时自动将字段设置为现在。 对“上次修改”时间戳很有用。 注意当前日期是 ''always'' used; 它不仅仅是您可以覆盖的默认值。</p>
for &quot;last-modified&quot; timestamps. Note that the current date is ''always''
+
<p>该字段仅在调用 [[../instances#django.db.models.Model|Model.save()]] 时自动更新。 以其他方式(例如 [[../querysets#django.db.models.query.QuerySet|QuerySet.update()]])更新其他字段时,该字段不会更新,但您可以在这样的更新中为该字段指定自定义值。</p></dd></dl>
used; it's not just a default value that you can override.</p>
 
<p>The field is only automatically updated when calling [[../instances#django.db.models.Model|<code>Model.save()</code>]]. The field isn't updated when making updates
 
to other fields in other ways such as [[../querysets#django.db.models.query.QuerySet|<code>QuerySet.update()</code>]], though you can specify a custom
 
value for the field in an update like that.</p></dd></dl>
 
  
; <code>DateField.</code><code>auto_now_add</code>
+
; <span class="sig-prename descclassname"><span class="pre">DateField.</span></span><span class="sig-name descname"><span class="pre">auto_now_add</span></span>
: Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is ''always'' used; it's not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of <code>auto_now_add=True</code>:
+
: 首次创建对象时自动将字段设置为现在。 用于创建时间戳。 注意当前日期是 ''always'' used; 它不仅仅是您可以覆盖的默认值。 所以即使你在创建对象时为这个字段设置了一个值,它也会被忽略。 如果您希望能够修改此字段,请设置以下内容而不是 <code>auto_now_add=True</code>
;* For [[#django.db.models.DateField|<code>DateField</code>]]: <code>default=date.today</code> - from <code>datetime.date.today()</code>
+
;* 对于 [[#django.db.models.DateField|DateField]]<code>default=date.today</code> - 来自 <code>datetime.date.today()</code>
;* For [[#django.db.models.DateTimeField|<code>DateTimeField</code>]]: <code>default=timezone.now</code> - from [[../../utils#django.utils.timezone|<code>django.utils.timezone.now()</code>]]
+
;* 对于 [[#django.db.models.DateTimeField|DateTimeField]]<code>default=timezone.now</code> - 来自 [[../../utils#django.utils.timezone|django.utils.timezone.now()]]
  
The default form widget for this field is a
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]。 管理员添加了一个 JavaScript 日历和一个“今天”的快捷方式。 包括一个额外的 <code>invalid_date</code> 错误消息密钥。
[[../../forms/widgets#django.forms|<code>TextInput</code>]]. The admin adds a JavaScript calendar,
 
and a shortcut for &quot;Today&quot;. Includes an additional <code>invalid_date</code> error
 
message key.
 
  
The options <code>auto_now_add</code>, <code>auto_now</code>, and <code>default</code> are mutually exclusive.
+
选项 <code>auto_now_add</code><code>auto_now</code> <code>default</code> 是互斥的。 这些选项的任何组合都会导致错误。
Any combination of these options will result in an error.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
As currently implemented, setting <code>auto_now</code> or <code>auto_now_add</code> to
+
按照目前的实施,将 <code>auto_now</code> <code>auto_now_add</code> 设置为 <code>True</code> 将导致字段设置为 <code>editable=False</code> <code>blank=True</code>
<code>True</code> will cause the field to have <code>editable=False</code> and <code>blank=True</code>
 
set.
 
  
  
第666行: 第543行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
The <code>auto_now</code> and <code>auto_now_add</code> options will always use the date in
+
<code>auto_now</code> <code>auto_now_add</code> 选项将始终使用创建或更新时 [[../../../topics/i18n/timezones#default-current-time-zone|默认时区]] 中的日期。 如果您需要不同的东西,您可能需要考虑简单地使用您自己的可调用默认值或覆盖 <code>save()</code> 而不是使用 <code>auto_now</code> <code>auto_now_add</code>; 或者使用 <code>DateTimeField</code> 而不是 <code>DateField</code> 并决定如何在显示时间处理从日期时间到日期的转换。
the [[../../../topics/i18n/timezones#default-current-time-zone|<span class="std std-ref">default timezone</span>]] at the moment of
 
creation or update. If you need something different, you may want to
 
consider simply using your own callable default or overriding <code>save()</code>
 
instead of using <code>auto_now</code> or <code>auto_now_add</code>; or using a
 
<code>DateTimeField</code> instead of a <code>DateField</code> and deciding how to handle the
 
conversion from datetime to date at display time.
 
  
  
第682行: 第553行:
 
<div id="datetimefield" class="section">
 
<div id="datetimefield" class="section">
  
=== <code>DateTimeField</code> ===
+
=== DateTimeField ===
  
; ''class'' <code>DateTimeField</code><span class="sig-paren">(</span>''<span class="n">auto_now</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">auto_now_add</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#DateTimeField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">DateTimeField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">auto_now</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">auto_now_add</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A date and time, represented in Python by a <code>datetime.datetime</code> instance.
+
日期和时间,在 Python 中由 <code>datetime.datetime</code> 实例表示。 采用与 [[#django.db.models.DateField|DateField]] 相同的额外参数。
Takes the same extra arguments as [[#django.db.models.DateField|<code>DateField</code>]].
 
  
The default form widget for this field is a single
+
此字段的默认表单小部件是单个 [[../../forms/widgets#django.forms|TextInput]]。 管理员使用两个单独的 [[../../forms/widgets#django.forms|TextInput]] 小部件和 JavaScript 快捷方式。
[[../../forms/widgets#django.forms|<code>TextInput</code>]]. The admin uses two separate
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]] widgets with JavaScript shortcuts.
 
  
  
第698行: 第566行:
 
<div id="decimalfield" class="section">
 
<div id="decimalfield" class="section">
  
=== <code>DecimalField</code> ===
+
=== DecimalField ===
  
; ''class'' <code>DecimalField</code><span class="sig-paren">(</span>''<span class="n">max_digits</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">decimal_places</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#DecimalField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">DecimalField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_digits</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">decimal_places</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A fixed-precision decimal number, represented in Python by a
+
一个固定精度的十进制数,在 Python 中由 <code>Decimal</code> 实例表示。 它使用 [[../../validators#django.core.validators|DecimalValidator]] 验证输入。
<code>Decimal</code> instance. It validates the input using
 
[[../../validators#django.core.validators|<code>DecimalValidator</code>]].
 
  
Has two '''required''' arguments:
+
有两个 '''required''' 参数:
  
; <code>DecimalField.</code><code>max_digits</code>
+
; <span class="sig-prename descclassname"><span class="pre">DecimalField.</span></span><span class="sig-name descname"><span class="pre">max_digits</span></span>
: The maximum number of digits allowed in the number. Note that this number must be greater than or equal to <code>decimal_places</code>.
+
: 号码中允许的最大位数。 请注意,此数字必须大于或等于 <code>decimal_places</code>
  
; <code>DecimalField.</code><code>decimal_places</code>
+
; <span class="sig-prename descclassname"><span class="pre">DecimalField.</span></span><span class="sig-name descname"><span class="pre">decimal_places</span></span>
: The number of decimal places to store with the number.
+
: 与数字一起存储的小数位数。
  
For example, to store numbers up to <code>999</code> with a resolution of 2 decimal
+
例如,要以 2 个小数位的分辨率存储高达 <code>999</code> 的数字,您可以使用:
places, you'd use:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第722行: 第587行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>models.DecimalField(..., max_digits=5, decimal_places=2)</pre>
+
<syntaxhighlight lang="python">models.DecimalField(..., max_digits=5, decimal_places=2)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
And to store numbers up to approximately one billion with a resolution of 10
+
并以 10 位小数的分辨率存储多达约 10 亿的数字:
decimal places:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第734行: 第598行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>models.DecimalField(..., max_digits=19, decimal_places=10)</pre>
+
<syntaxhighlight lang="python">models.DecimalField(..., max_digits=19, decimal_places=10)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>NumberInput</code>]]
+
[[../../forms/fields#django.forms.Field|localize]] 为 <code>False</code> [[../../forms/widgets#django.forms|TextInput]] 时,此字段的默认表单小部件为 [[../../forms/widgets#django.forms|NumberInput]]
when [[../../forms/fields#django.forms.Field|<code>localize</code>]] is <code>False</code> or
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]] otherwise.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
For more information about the differences between the
+
有关两者之间差异的更多信息[[#django.db.models.FloatField|浮动字段]][[#django.db.models.DecimalField|十进制字段]]类,请看 FloatField 对比 十进制字段 . 您还应该了解十进制字段的 [[../../databases#sqlite-decimal-handling|SQLite 限制]]
[[#django.db.models.FloatField|<code>FloatField</code>]] and [[#django.db.models.DecimalField|<code>DecimalField</code>]] classes, please
 
see [[#floatfield-vs-decimalfield|<span class="std std-ref">FloatField vs. DecimalField</span>]]. You
 
should also be aware of [[../../databases#sqlite-decimal-handling|<span class="std std-ref">SQLite limitations</span>]]
 
of decimal fields.
 
  
  
第759行: 第617行:
 
<div id="durationfield" class="section">
 
<div id="durationfield" class="section">
  
=== <code>DurationField</code> ===
+
=== DurationField ===
  
; ''class'' <code>DurationField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#DurationField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">DurationField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A field for storing periods of time - modeled in Python by
+
用于存储时间段的字段 - <code>timedelta</code> 在 Python 中建模。 在 PostgreSQL 上使用时,使用的数据类型是 <code>interval</code>,而在 Oracle 上,数据类型是 <code>INTERVAL DAY(9) TO SECOND(6)</code>。 否则使用微秒的 <code>bigint</code>
<code>timedelta</code>. When used on PostgreSQL, the data type
 
used is an <code>interval</code> and on Oracle the data type is <code>INTERVAL DAY(9) TO SECOND(6)</code>. Otherwise a <code>bigint</code> of microseconds is used.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
Arithmetic with <code>DurationField</code> works in most cases. However on all
+
使用 <code>DurationField</code> 的算术在大多数情况下都有效。 但是,在除 PostgreSQL 之外的所有数据库上,将 <code>DurationField</code> 的值与 <code>DateTimeField</code> 实例上的算术进行比较将无法按预期工作。
databases other than PostgreSQL, comparing the value of a <code>DurationField</code>
 
to arithmetic on <code>DateTimeField</code> instances will not work as expected.
 
  
  
第782行: 第636行:
 
<div id="emailfield" class="section">
 
<div id="emailfield" class="section">
  
=== <code>EmailField</code> ===
+
=== EmailField ===
  
; ''class'' <code>EmailField</code><span class="sig-paren">(</span>''<span class="n">max_length</span><span class="o">=</span><span class="default_value">254</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#EmailField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">EmailField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">254</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A [[#django.db.models.CharField|<code>CharField</code>]] that checks that the value is a valid email address using
+
[[#django.db.models.CharField|CharField]] 使用 [[../../validators#django.core.validators|EmailValidator]] 检查值是否是有效的电子邮件地址。
[[../../validators#django.core.validators|<code>EmailValidator</code>]].
 
  
  
第794行: 第647行:
 
<div id="filefield" class="section">
 
<div id="filefield" class="section">
  
=== <code>FileField</code> ===
+
=== FileField ===
  
; ''class'' <code>FileField</code><span class="sig-paren">(</span>''<span class="n">upload_to</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">max_length</span><span class="o">=</span><span class="default_value">100</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#FileField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">FileField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">upload_to</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A file-upload field.
+
一个文件上传字段
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
The <code>primary_key</code> argument isn't supported and will raise an error if
+
不支持 <code>primary_key</code> 参数,如果使用会引发错误。
used.
 
  
  
 
</div>
 
</div>
Has two optional arguments:
+
有两个可选参数:
  
 
<dl>
 
<dl>
<dt><code>FileField.</code><code>upload_to</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">FileField.</span></span><span class="sig-name descname"><span class="pre">upload_to</span></span></dt>
<dd><p>This attribute provides a way of setting the upload directory and file name,
+
<dd><p>该属性提供了一种设置上传目录和文件名的方式,可以通过两种方式进行设置。 在这两种情况下,值都会传递给 [[../../files/storage#django.core.files.storage.Storage|Storage.save()]] 方法。</p>
and can be set in two ways. In both cases, the value is passed to the
+
<p>如果您指定一个字符串值,它可能包含 <code>strftime()</code> 格式,它将被文件上传的日期/时间替换(这样上传的文件不会填满给定的目录)。 例如:</p>
[[../../files/storage#django.core.files.storage.Storage|<code>Storage.save()</code>]] method.</p>
 
<p>If you specify a string value, it may contain <code>strftime()</code>
 
formatting, which will be replaced by the date/time of the file upload (so
 
that uploaded files don't fill up the given directory). For example:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class MyModel(models.Model):
+
<syntaxhighlight lang="python">class MyModel(models.Model):
 
     # file will be uploaded to MEDIA_ROOT/uploads
 
     # file will be uploaded to MEDIA_ROOT/uploads
 
     upload = models.FileField(upload_to='uploads/')
 
     upload = models.FileField(upload_to='uploads/')
 
     # or...
 
     # or...
 
     # file will be saved to MEDIA_ROOT/uploads/2015/01/30
 
     # file will be saved to MEDIA_ROOT/uploads/2015/01/30
     upload = models.FileField(upload_to='uploads/%Y/%m/%d/')</pre>
+
     upload = models.FileField(upload_to='uploads/%Y/%m/%d/')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If you are using the default
+
<p>如果您使用默认的 [[../../files/storage#django.core.files.storage|FileSystemStorage]],则字符串值将附加到您的 [[#id5|:setting:`MEDIA_ROOT`]] 路径以形成本地文件系统上将存储上传文件的位置。 如果您使用不同的存储,请查看该存储的文档以了解它如何处理 <code>upload_to</code></p>
[[../../files/storage#django.core.files.storage|<code>FileSystemStorage</code>]], the string value
+
<p><code>upload_to</code> 也可以是可调用的,例如函数。 这将被调用以获取上传路径,包括文件名。 这个可调用对象必须接受两个参数并返回要传递给存储系统的 Unix 样式路径(带正斜杠)。 这两个论点是:</p>
will be appended to your [[../../settings#std-setting-MEDIA_ROOT|<code>MEDIA_ROOT</code>]] path to form the location on
 
the local filesystem where uploaded files will be stored. If you are using
 
a different storage, check that storage's documentation to see how it
 
handles <code>upload_to</code>.</p>
 
<p><code>upload_to</code> may also be a callable, such as a function. This will be
 
called to obtain the upload path, including the filename. This callable must
 
accept two arguments and return a Unix-style path (with forward slashes)
 
to be passed along to the storage system. The two arguments are:</p>
 
 
{|
 
{|
!width="32%"| <p>Argument</p>
+
!width="32%"| <p>参数</p>
 
!width="68%"| <p>描述</p>
 
!width="68%"| <p>描述</p>
 
|-
 
|-
 
| <p><code>instance</code></p>
 
| <p><code>instance</code></p>
 
|
 
|
<p>An instance of the model where the
+
<p>定义了 <code>FileField</code> 的模型实例。 更具体地说,这是附加当前文件的特定实例。</p>
<code>FileField</code> is defined. More specifically,
+
<p>在大多数情况下,这个对象还没有被保存到数据库中,所以如果它使用默认的 <code>AutoField</code>'',它的主键字段'' 可能还没有值。</p>
this is the particular instance where the
 
current file is being attached.</p>
 
<p>In most cases, this object will not have been
 
saved to the database yet, so if it uses the
 
default <code>AutoField</code>, ''it might not yet have a
 
value for its primary key field''.</p>
 
 
|-
 
|-
 
| <p><code>filename</code></p>
 
| <p><code>filename</code></p>
| <p>The filename that was originally given to the
+
| <p>最初赋予文件的文件名。 在确定最终目的地路径时,可能会或可能不会考虑这一点。</p>
file. This may or may not be taken into account
 
when determining the final destination path.</p>
 
 
|}
 
|}
  
<p>例子:</p>
+
<p>例如:</p>
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def user_directory_path(instance, filename):
+
<syntaxhighlight lang="python">def user_directory_path(instance, filename):
     # file will be uploaded to MEDIA_ROOT/user_&lt;id&gt;/&lt;filename&gt;
+
     # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
 
     return 'user_{0}/{1}'.format(instance.user.id, filename)
 
     return 'user_{0}/{1}'.format(instance.user.id, filename)
  
 
class MyModel(models.Model):
 
class MyModel(models.Model):
     upload = models.FileField(upload_to=user_directory_path)</pre>
+
     upload = models.FileField(upload_to=user_directory_path)</syntaxhighlight>
  
 
</div>
 
</div>
第881行: 第713行:
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>FileField.</code><code>storage</code>
+
; <span class="sig-prename descclassname"><span class="pre">FileField.</span></span><span class="sig-name descname"><span class="pre">storage</span></span>
: A storage object, which handles the storage and retrieval of your files. See [[../../../topics/files|<span class="doc">管理文件</span>]] for details on how to provide this object.
+
: 一个存储对象,用于处理文件的存储和检索。 有关如何提供此对象的详细信息,请参阅 [[../../../topics/files|管理文件]]
  
The default form widget for this field is a
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|ClearableFileInput]]
[[../../forms/widgets#django.forms|<code>ClearableFileInput</code>]].
 
  
Using a [[#django.db.models.FileField|<code>FileField</code>]] or an [[#django.db.models.ImageField|<code>ImageField</code>]] (see below) in a model
+
在模型中使用 [[#django.db.models.FileField|FileField]] [[#django.db.models.ImageField|ImageField]](见下文)需要几个步骤:
takes a few steps:
 
  
# 在你的 setting 文件中,你需要定义:setting: MEDIA_ROOT 作为 Django 存储上传文件目录的完整路径。(为了提高性能,这些文件不会储存在数据库中)定义: setting: MEDIA_URL 作为该目录的基本公共 URL, 确保该目录能够被 Web 服务器的是用户写入。
+
# 在您的设置文件中,您需要将 [[#id7|:setting:`MEDIA_ROOT`]] 定义为您希望 Django 存储上传文件的目录的完整路径。 (为了性能,这些文件不存储在数据库中。)将 [[#id9|:setting:`MEDIA_URL`]] 定义为该目录的基本公共 URL。 确保该目录可由 Web 服务器的用户帐户写入。
# Add the [[#django.db.models.FileField|<code>FileField</code>]] or [[#django.db.models.ImageField|<code>ImageField</code>]] to your model, defining the [[#django.db.models.FileField.upload_to|<code>upload_to</code>]] option to specify a subdirectory of [[../../settings#std-setting-MEDIA_ROOT|<code>MEDIA_ROOT</code>]] to use for uploaded files.
+
# [[#django.db.models.FileField|FileField]] [[#django.db.models.ImageField|ImageField]] 添加到您的模型中,定义 [[#django.db.models.FileField.upload_to|upload_to]] 选项以指定要使用的 [[#id11|:setting:`MEDIA_ROOT`]] 的子目录对于上传的文件。
# All that will be stored in your database is a path to the file (relative to [[../../settings#std-setting-MEDIA_ROOT|<code>MEDIA_ROOT</code>]]). You'll most likely want to use the convenience [[#django.db.models.fields.files.FieldFile.url|<code>url</code>]] attribute provided by Django. For example, if your [[#django.db.models.ImageField|<code>ImageField</code>]] is called <code>mug_shot</code>, you can get the absolute path to your image in a template with <code>{{ object.mug_shot.url }}</code>.
+
# 所有将存储在您的数据库中的是文件的路径(相对于 [[#id13|:setting:`MEDIA_ROOT`]])。 您很可能希望使用 Django 提供的便利 [[#django.db.models.fields.files.FieldFile.url|url]] 属性。 例如,如果您的 [[#django.db.models.ImageField|ImageField]] 被称为 <code>mug_shot</code>,您可以使用 <code>{{ object.mug_shot.url }}</code> 在模板中获取图像的绝对路径。
  
For example, say your [[../../settings#std-setting-MEDIA_ROOT|<code>MEDIA_ROOT</code>]] is set to <code>'/home/media'</code>, and
+
例如,假设您的 [[#id15|:setting:`MEDIA_ROOT`]] 设置为 <code>'/home/media'</code>,而 [[#django.db.models.FileField.upload_to|upload_to]] 设置为 <code>'photos/%Y/%m/%d'</code>[[#django.db.models.FileField.upload_to|upload_to]]的<code>'%Y/%m/%d'</code>部分为<code>strftime()</code>格式; <code>'%Y'</code> 是四位数年份,<code>'%m'</code> 是两位数月份,<code>'%d'</code> 是两位数日。 如果您在 1 月上传文件 2007 年 15 月 15 日,它将保存在目录 <code>/home/media/photos/2007/01/15</code> 中。
[[#django.db.models.FileField.upload_to|<code>upload_to</code>]] is set to <code>'photos/%Y/%m/%d'</code>. The <code>'%Y/%m/%d'</code>
 
part of [[#django.db.models.FileField.upload_to|<code>upload_to</code>]] is <code>strftime()</code> formatting;
 
<code>'%Y'</code> is the four-digit year, <code>'%m'</code> is the two-digit month and <code>'%d'</code> is
 
the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
 
the directory <code>/home/media/photos/2007/01/15</code>.
 
  
If you wanted to retrieve the uploaded file's on-disk filename, or the file's
+
如果要检索上传文件的磁盘文件名或文件大小,可以分别使用 [[../../files/file#django.core.files.File|name]] [[../../files/file#django.core.files.File|size]] 属性; 有关可用属性和方法的更多信息,请参阅 [[../../files/file#django.core.files|File]] 类参考和 [[../../../topics/files|Managing files]] 主题指南。
size, you could use the [[../../files/file#django.core.files.File|<code>name</code>]] and
 
[[../../files/file#django.core.files.File|<code>size</code>]] attributes respectively; for more
 
information on the available attributes and methods, see the
 
[[../../files/file#django.core.files|<code>File</code>]] class reference and the [[../../../topics/files|<span class="doc">管理文件</span>]]
 
topic guide.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
 
文件在数据库中作为保存模型的一部分,因此在模型被保存之前,不能依赖磁盘上使用的实际文件名。
 
文件在数据库中作为保存模型的一部分,因此在模型被保存之前,不能依赖磁盘上使用的实际文件名。
第916行: 第736行:
  
 
</div>
 
</div>
The uploaded file's relative URL can be obtained using the
+
上传文件的相对 URL 可以通过 [[#django.db.models.fields.files.FieldFile.url|url]] 属性获取。 在内部,这会调用底层 [[../../files/storage#django.core.files.storage|Storage]] 类的 [[../../files/storage#django.core.files.storage.Storage|url()]] 方法。
[[#django.db.models.fields.files.FieldFile.url|<code>url</code>]] attribute. Internally,
 
this calls the [[../../files/storage#django.core.files.storage.Storage|<code>url()</code>]] method of the
 
underlying [[../../files/storage#django.core.files.storage|<code>Storage</code>]] class.
 
  
Note that whenever you deal with uploaded files, you should pay close attention
+
请注意,无论何时处理上传的文件,都应密切注意上传文件的位置和文件类型,以避免出现安全漏洞。 ''验证所有上传的文件'',以便您确定这些文件是您认为的那样。 例如,如果您盲目地让某人在未经验证的情况下将文件上传到您的 Web 服务器文档根目录中的目录,那么有人可以上传 CGI PHP 脚本并通过访问其在您站点上的 URL 来执行该脚本。 不允许这样。
to where you're uploading them and what type of files they are, to avoid
 
security holes. ''Validate all uploaded files'' so that you're sure the files are
 
what you think they are. For example, if you blindly let somebody upload files,
 
without validation, to a directory that's within your Web server's document
 
root, then somebody could upload a CGI or PHP script and execute that script by
 
visiting its URL on your site. Don't allow that.
 
  
Also note that even an uploaded HTML file, since it can be executed by the
+
另外要注意的是,即使是上传的 HTML 文件,由于可以被浏览器执行(虽然不能被服务器执行),也会造成相当于 XSS CSRF 攻击的安全威胁。
browser (though not by the server), can pose security threats that are
 
equivalent to XSS or CSRF attacks.
 
  
[[#django.db.models.FileField|<code>FileField</code>]] instances are created in your database as <code>varchar</code>
+
[[#django.db.models.FileField|FileField]] 实例在您的数据库中创建为 <code>varchar</code> 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 [[#django.db.models.CharField.max_length|max_length]] 参数更改最大长度。
columns with a default max length of 100 characters. As with other fields, you
 
can change the maximum length using the [[#django.db.models.CharField.max_length|<code>max_length</code>]] argument.
 
  
 
<div id="filefield-and-fieldfile" class="section">
 
<div id="filefield-and-fieldfile" class="section">
  
==== <code>FileField````FieldFile</code> ====
+
==== FileField 和 FieldFile ====
  
; ''class'' <code>FieldFile</code>[[../../_modules/django/db/models/fields/files.html#FieldFile|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">FieldFile</span></span>
 
:  
 
:  
  
When you access a [[#django.db.models.FileField|<code>FileField</code>]] on a model, you are
+
当您访问模型上的 [[#django.db.models.FileField|FileField]] 时,您将获得一个 [[#django.db.models.fields.files.FieldFile|FieldFile]] 实例作为访问底层文件的代理。
given an instance of [[#django.db.models.fields.files.FieldFile|<code>FieldFile</code>]] as a proxy for accessing the underlying
 
file.
 
  
The API of [[#django.db.models.fields.files.FieldFile|<code>FieldFile</code>]] mirrors that of [[../../files/file#django.core.files|<code>File</code>]],
+
[[#django.db.models.fields.files.FieldFile|FieldFile]] 的 API 与 [[../../files/file#django.core.files|File]] 的 API 相同,有一个关键区别:''类包装的对象不一定是 Python 内置文件对象的包装器。'' ] 相反,它是 [[../../files/storage#django.core.files.storage.Storage|Storage.open()]] 方法的结果的包装器,它可能是一个 [[../../files/file#django.core.files|File]] 对象,或者它可能是 [[../files/file.html#django.core.files.File|的自定义存储实现]文件]] API。
with one key difference: ''The object wrapped by the class is not necessarily a
 
wrapper around Python's built-in file object.'' Instead, it is a wrapper around
 
the result of the [[../../files/storage#django.core.files.storage.Storage|<code>Storage.open()</code>]]
 
method, which may be a [[../../files/file#django.core.files|<code>File</code>]] object, or it may be a
 
custom storage's implementation of the [[../../files/file#django.core.files|<code>File</code>]] API.
 
  
In addition to the API inherited from [[../../files/file#django.core.files|<code>File</code>]] such as
+
除了继承自 [[../../files/file#django.core.files|File]] 的 API,如 <code>read()</code> <code>write()</code>[[#django.db.models.fields.files.FieldFile|FieldFile]] 还包括几个可以用来与底层文件交互的方法:
<code>read()</code> and <code>write()</code>, [[#django.db.models.fields.files.FieldFile|<code>FieldFile</code>]] includes several methods that
 
can be used to interact with the underlying file:
 
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第963行: 第761行:
 
警告
 
警告
  
Two methods of this class, [[#django.db.models.fields.files.FieldFile.save|<code>save()</code>]] and
+
该类的两个方法[[#django.db.models.fields.files.FieldFile.save|save()]][[#django.db.models.fields.files.FieldFile.delete|delete()]],默认将关联的<code>FieldFile</code>的模型对象保存在数据库中。
[[#django.db.models.fields.files.FieldFile.delete|<code>delete()</code>]], default to saving the model object of the
 
associated <code>FieldFile</code> in the database.
 
  
  
 
</div>
 
</div>
; <code>FieldFile.</code><code>name</code>
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">name</span></span>
 
:  
 
:  
  
The name of the file including the relative path from the root of the
+
文件的名称,包括从相关 [[#django.db.models.FileField|FileField]] 的 [[../../files/storage#django.core.files.storage|Storage]] 的根的相对路径。
[[../../files/storage#django.core.files.storage|<code>Storage</code>]] of the associated
 
[[#django.db.models.FileField|<code>FileField</code>]].
 
  
; <code>FieldFile.</code><code>size</code>
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">size</span></span>
 
:  
 
:  
  
The result of the underlying [[../../files/storage#django.core.files.storage.Storage|<code>Storage.size()</code>]] method.
+
底层 [[../../files/storage#django.core.files.storage.Storage|Storage.size()]] 方法的结果。
  
; <code>FieldFile.</code><code>url</code>
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">url</span></span>
 
:  
 
:  
  
A read-only property to access the file's relative URL by calling the
+
通过调用底层 [[../../files/storage#django.core.files.storage|Storage]] 类的 [[../../files/storage#django.core.files.storage.Storage|url()]] 方法访问文件的相对 URL 的只读属性。
[[../../files/storage#django.core.files.storage.Storage|<code>url()</code>]] method of the underlying
 
[[../../files/storage#django.core.files.storage|<code>Storage</code>]] class.
 
  
; <code>FieldFile.</code><code>open</code><span class="sig-paren">(</span>''<span class="n">mode</span><span class="o">=</span><span class="default_value">'rb'</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#FieldFile.open|<span class="viewcode-link">[源代码]</span>]]
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">open</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'rb'</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Opens or reopens the file associated with this instance in the specified
+
在指定的 <code>mode</code> 中打开或重新打开与此实例关联的文件。 与标准 Python <code>open()</code> 方法不同,它不返回文件描述符。
<code>mode</code>. Unlike the standard Python <code>open()</code> method, it doesn't return a
 
file descriptor.
 
  
Since the underlying file is opened implicitly when accessing it, it may be
+
由于底层文件在访问时是隐式打开的,因此除了重置指向底层文件的指针或更改<code>mode</code>之外,可能没有必要调用此方法。
unnecessary to call this method except to reset the pointer to the underlying
 
file or to change the <code>mode</code>.
 
  
; <code>FieldFile.</code><code>close</code><span class="sig-paren">(</span><span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#FieldFile.close|<span class="viewcode-link">[源代码]</span>]]
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
 
:  
 
:  
  
Behaves like the standard Python <code>file.close()</code> method and closes the file
+
行为类似于标准 Python <code>file.close()</code> 方法并关闭与此实例关联的文件。
associated with this instance.
 
  
; <code>FieldFile.</code><code>save</code><span class="sig-paren">(</span>''<span class="n">name</span>'', ''<span class="n">content</span>'', ''<span class="n">save</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#FieldFile.save|<span class="viewcode-link">[源代码]</span>]]
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">save</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>'', ''<span class="n"><span class="pre">content</span></span>'', ''<span class="n"><span class="pre">save</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
This method takes a filename and file contents and passes them to the storage
+
此方法获取文件名和文件内容,并将它们传递给字段的存储类,然后将存储的文件与模型字段相关联。 如果您想手动将文件数据与模型上的 [[#django.db.models.FileField|FileField]] 实例相关联,可以使用 <code>save()</code> 方法来保存该文件数据。
class for the field, then associates the stored file with the model field.
 
If you want to manually associate file data with
 
[[#django.db.models.FileField|<code>FileField</code>]] instances on your model, the <code>save()</code>
 
method is used to persist that file data.
 
  
Takes two required arguments: <code>name</code> which is the name of the file, and
+
接受两个必需的参数:<code>name</code> 是文件名,<code>content</code> 是一个包含文件内容的对象。 可选的 <code>save</code> 参数控制在更改与此字段关联的文件后是否保存模型实例。 默认为 <code>True</code>
<code>content</code> which is an object containing the file's contents. The
 
optional <code>save</code> argument controls whether or not the model instance is
 
saved after the file associated with this field has been altered. Defaults to
 
<code>True</code>.
 
  
Note that the <code>content</code> argument should be an instance of
+
请注意, <code>content</code> 参数应该是 [[../../files/file#django.core.files|django.core.files.File]] 的实例,而不是 Python 的内置文件对象。 您可以从现有的 Python 文件对象构造一个 [[../../files/file#django.core.files|File]],如下所示:
[[../../files/file#django.core.files|<code>django.core.files.File</code>]], not Python's built-in file object.
 
You can construct a [[../../files/file#django.core.files|<code>File</code>]] from an existing
 
Python file object like this:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,029行: 第805行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.core.files import File
+
<syntaxhighlight lang="python">from django.core.files import File
 
# Open an existing file using Python's built-in open()
 
# Open an existing file using Python's built-in open()
 
f = open('/path/to/hello.world')
 
f = open('/path/to/hello.world')
myfile = File(f)</pre>
+
myfile = File(f)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Or you can construct one from a Python string like this:
+
或者,您可以从 Python 字符串中构造一个,如下所示:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,043行: 第819行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.core.files.base import ContentFile
+
<syntaxhighlight lang="python">from django.core.files.base import ContentFile
myfile = ContentFile(&quot;hello world&quot;)</pre>
+
myfile = ContentFile("hello world")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For more information, see [[../../../topics/files|<span class="doc">管理文件</span>]].
+
有关更多信息,请参阅 [[../../../topics/files|管理文件]]
  
; <code>FieldFile.</code><code>delete</code><span class="sig-paren">(</span>''<span class="n">save</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#FieldFile.delete|<span class="viewcode-link">[源代码]</span>]]
+
; <span class="sig-prename descclassname"><span class="pre">FieldFile.</span></span><span class="sig-name descname"><span class="pre">delete</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">save</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Deletes the file associated with this instance and clears all attributes on
+
删除与此实例关联的文件并清除该字段的所有属性。 注意:如果在调用 <code>delete()</code> 时碰巧打开了该文件,则此方法将关闭该文件。
the field. Note: This method will close the file if it happens to be open when
 
<code>delete()</code> is called.
 
  
The optional <code>save</code> argument controls whether or not the model instance is
+
可选的 <code>save</code> 参数控制在删除与此字段关联的文件后是否保存模型实例。 默认为 <code>True</code>
saved after the file associated with this field has been deleted. Defaults to
 
<code>True</code>.
 
  
Note that when a model is deleted, related files are not deleted. If you need
+
请注意,删除模型时,不会删除相关文件。 如果您需要清理孤立文件,则需要自己处理(例如,使用自定义管理命令可以手动运行或安排定期运行,例如 cron)。
to cleanup orphaned files, you'll need to handle it yourself (for instance,
 
with a custom management command that can be run manually or scheduled to run
 
periodically via e.g. cron).
 
  
  
第1,073行: 第842行:
 
<div id="filepathfield" class="section">
 
<div id="filepathfield" class="section">
  
=== <code>FilePathField</code> ===
+
=== FilePathField ===
  
; ''class'' <code>FilePathField</code><span class="sig-paren">(</span>''<span class="n">path</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">match</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">recursive</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">max_length</span><span class="o">=</span><span class="default_value">100</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#FilePathField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">FilePathField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">path</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">match</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">recursive</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A [[#django.db.models.CharField|<code>CharField</code>]] whose choices are limited to the filenames in a certain
+
A [[#django.db.models.CharField|CharField]] 其选择仅限于文件系统上某个目录中的文件名。 有三个特殊参数,其中第一个是 '''required'''
directory on the filesystem. Has three special arguments, of which the first is
 
'''required''':
 
  
; <code>FilePathField.</code><code>path</code>
+
; <span class="sig-prename descclassname"><span class="pre">FilePathField.</span></span><span class="sig-name descname"><span class="pre">path</span></span>
: Required. The absolute filesystem path to a directory from which this [[#django.db.models.FilePathField|<code>FilePathField</code>]] should get its choices. Example: <code>&quot;/home/images&quot;</code>.
+
: 必需的。 此 [[#django.db.models.FilePathField|FilePathField]] 应从中获取其选择的目录的绝对文件系统路径。 示例:<code>&quot;/home/images&quot;</code>
  
; <code>FilePathField.</code><code>match</code>
+
; <span class="sig-prename descclassname"><span class="pre">FilePathField.</span></span><span class="sig-name descname"><span class="pre">match</span></span>
: Optional. A regular expression, as a string, that [[#django.db.models.FilePathField|<code>FilePathField</code>]] will use to filter filenames. Note that the regex will be applied to the base filename, not the full path. Example: <code>&quot;foo.*\.txt$&quot;</code>, which will match a file called <code>foo23.txt</code> but not <code>bar.txt</code> or <code>foo23.png</code>.
+
: 可选的。 [[#django.db.models.FilePathField|FilePathField]] 将用于过滤文件名的正则表达式,作为字符串。 请注意,正则表达式将应用于基本文件名,而不是完整路径。 示例:<code>&quot;foo.*\.txt$&quot;</code>,它将匹配名为 <code>foo23.txt</code> 但不匹配 <code>bar.txt</code> <code>foo23.png</code> 的文件。
  
; <code>FilePathField.</code><code>recursive</code>
+
; <span class="sig-prename descclassname"><span class="pre">FilePathField.</span></span><span class="sig-name descname"><span class="pre">recursive</span></span>
: Optional. Either <code>True</code> or <code>False</code>. Default is <code>False</code>. Specifies whether all subdirectories of [[#django.db.models.FilePathField.path|<code>path</code>]] should be included
+
: 可选的。 <code>True</code> <code>False</code>。 默认值为 <code>False</code>。 指定是否应包含 [[#django.db.models.FilePathField.path|path]] 的所有子目录
  
; <code>FilePathField.</code><code>allow_files</code>
+
; <span class="sig-prename descclassname"><span class="pre">FilePathField.</span></span><span class="sig-name descname"><span class="pre">allow_files</span></span>
: Optional. Either <code>True</code> or <code>False</code>. Default is <code>True</code>. Specifies whether files in the specified location should be included. Either this or [[#django.db.models.FilePathField.allow_folders|<code>allow_folders</code>]] must be <code>True</code>.
+
: 可选的。 <code>True</code> <code>False</code>。 默认值为 <code>True</code>。 指定是否应包含指定位置的文件。 此或 [[#django.db.models.FilePathField.allow_folders|allow_folders]] 必须为 <code>True</code>
  
; <code>FilePathField.</code><code>allow_folders</code>
+
; <span class="sig-prename descclassname"><span class="pre">FilePathField.</span></span><span class="sig-name descname"><span class="pre">allow_folders</span></span>
: Optional. Either <code>True</code> or <code>False</code>. Default is <code>False</code>. Specifies whether folders in the specified location should be included. Either this or [[#django.db.models.FilePathField.allow_files|<code>allow_files</code>]] must be <code>True</code>.
+
: 可选的。 <code>True</code> <code>False</code>。 默认值为 <code>False</code>。 指定是否应包括指定位置的文件夹。 此或 [[#django.db.models.FilePathField.allow_files|allow_files]] 必须为 <code>True</code>
  
当然,这些参数能够同时使用。
+
当然,这些参数可以一起使用。
  
The one potential gotcha is that [[#django.db.models.FilePathField.match|<code>match</code>]] applies to the
+
一个潜在的问题是 [[#django.db.models.FilePathField.match|match]] 适用于基本文件名,而不是完整路径。 所以,这个例子:
base filename, not the full path. So, this example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,106行: 第872行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>FilePathField(path=&quot;/home/images&quot;, match=&quot;foo.*&quot;, recursive=True)</pre>
+
<syntaxhighlight lang="python">FilePathField(path="/home/images", match="foo.*", recursive=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
...will match <code>/home/images/foo.png</code> but not <code>/home/images/foo/bar.png</code>
+
...将匹配 <code>/home/images/foo.png</code> 但不匹配 <code>/home/images/foo/bar.png</code>,因为 [[#django.db.models.FilePathField.match|match]] 适用于基本文件名(<code>foo.png</code> <code>bar.png</code>)。
because the [[#django.db.models.FilePathField.match|<code>match</code>]] applies to the base filename
 
(<code>foo.png</code> and <code>bar.png</code>).
 
  
[[#django.db.models.FilePathField|<code>FilePathField</code>]] instances are created in your database as <code>varchar</code>
+
[[#django.db.models.FilePathField|FilePathField]] 实例在您的数据库中创建为 <code>varchar</code> 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 [[#django.db.models.CharField.max_length|max_length]] 参数更改最大长度。
columns with a default max length of 100 characters. As with other fields, you
 
can change the maximum length using the [[#django.db.models.CharField.max_length|<code>max_length</code>]] argument.
 
  
  
第1,123行: 第885行:
 
<div id="floatfield" class="section">
 
<div id="floatfield" class="section">
  
=== <code>FloatField</code> ===
+
=== FloatField ===
  
; ''class'' <code>FloatField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#FloatField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">FloatField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A floating-point number represented in Python by a <code>float</code> instance.
+
Python 中由 <code>float</code> 实例表示的浮点数。
  
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>NumberInput</code>]]
+
[[../../forms/fields#django.forms.Field|localize]] 为 <code>False</code> [[../../forms/widgets#django.forms|TextInput]] 时,此字段的默认表单小部件为 [[../../forms/widgets#django.forms|NumberInput]]
when [[../../forms/fields#django.forms.Field|<code>localize</code>]] is <code>False</code> or
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]] otherwise.
 
  
 
<div id="floatfield-vs-decimalfield" class="admonition-floatfield-vs-decimalfield admonition">
 
<div id="floatfield-vs-decimalfield" class="admonition-floatfield-vs-decimalfield admonition">
  
<code>FloatField</code> vs. <code>DecimalField</code>
+
<code>FloatField</code> 对比 <code>DecimalField</code>
  
The [[#django.db.models.FloatField|<code>FloatField</code>]] class is sometimes mixed up with the
+
[[#django.db.models.FloatField|FloatField]] 类有时会与 [[#django.db.models.DecimalField|DecimalField]] 类混淆。 虽然它们都代表实数,但它们代表这些数字的方式不同。 <code>FloatField</code> 在内部使用 Python <code>float</code> 类型,而 <code>DecimalField</code> 使用 Python <code>Decimal</code> 类型。 有关两者之间的区别的信息,请参阅 <code>decimal</code> 模块的 Python 文档。
[[#django.db.models.DecimalField|<code>DecimalField</code>]] class. Although they both represent real numbers, they
 
represent those numbers differently. <code>FloatField</code> uses Python's <code>float</code>
 
type internally, while <code>DecimalField</code> uses Python's <code>Decimal</code> type. For
 
information on the difference between the two, see Python's documentation
 
for the <code>decimal</code> module.
 
  
  
第1,151行: 第906行:
 
<div id="imagefield" class="section">
 
<div id="imagefield" class="section">
  
=== <code>ImageField</code> ===
+
=== ImageField ===
  
; ''class'' <code>ImageField</code><span class="sig-paren">(</span>''<span class="n">upload_to</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">height_field</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">width_field</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">max_length</span><span class="o">=</span><span class="default_value">100</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/files.html#ImageField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ImageField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">upload_to</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">height_field</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">width_field</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Inherits all attributes and methods from [[#django.db.models.FileField|<code>FileField</code>]], but also
+
[[#django.db.models.FileField|FileField]] 继承所有属性和方法,但也验证上传的对象是有效的图像。
validates that the uploaded object is a valid image.
 
  
In addition to the special attributes that are available for [[#django.db.models.FileField|<code>FileField</code>]],
+
除了可用于 [[#django.db.models.FileField|FileField]] 的特殊属性外,[[#django.db.models.ImageField|ImageField]] 还具有 <code>height</code> <code>width</code> 属性。
an [[#django.db.models.ImageField|<code>ImageField</code>]] also has <code>height</code> and <code>width</code> attributes.
 
  
To facilitate querying on those attributes, [[#django.db.models.ImageField|<code>ImageField</code>]] has two extra
+
为了方便查询这些属性,[[#django.db.models.ImageField|ImageField]] 有两个额外的可选参数:
optional arguments:
 
  
; <code>ImageField.</code><code>height_field</code>
+
; <span class="sig-prename descclassname"><span class="pre">ImageField.</span></span><span class="sig-name descname"><span class="pre">height_field</span></span>
: Name of a model field which will be auto-populated with the height of the image each time the model instance is saved.
+
: 模型字段的名称,每次保存模型实例时将自动填充图像的高度。
  
; <code>ImageField.</code><code>width_field</code>
+
; <span class="sig-prename descclassname"><span class="pre">ImageField.</span></span><span class="sig-name descname"><span class="pre">width_field</span></span>
: Name of a model field which will be auto-populated with the width of the image each time the model instance is saved.
+
: 模型字段的名称,每次保存模型实例时将自动填充图像的宽度。
  
Requires the [https://pillow.readthedocs.io/en/latest/ Pillow] library.
+
需要 [https://pillow.readthedocs.io/en/latest/ 枕头] 库。
  
[[#django.db.models.ImageField|<code>ImageField</code>]] instances are created in your database as <code>varchar</code>
+
[[#django.db.models.ImageField|ImageField]] 实例在您的数据库中创建为 <code>varchar</code> 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 [[#django.db.models.CharField.max_length|max_length]] 参数更改最大长度。
columns with a default max length of 100 characters. As with other fields, you
 
can change the maximum length using the [[#django.db.models.CharField.max_length|<code>max_length</code>]] argument.
 
  
The default form widget for this field is a
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|ClearableFileInput]]
[[../../forms/widgets#django.forms|<code>ClearableFileInput</code>]].
 
  
  
第1,184行: 第933行:
 
<div id="integerfield" class="section">
 
<div id="integerfield" class="section">
  
=== <code>IntegerField</code> ===
+
=== IntegerField ===
  
; ''class'' <code>IntegerField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#IntegerField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">IntegerField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
An integer. Values from <code>-2147483648</code> to <code>2147483647</code> are safe in all
+
一个整数。 从 <code>-2147483648</code> <code>2147483647</code> 的值在 Django 支持的所有数据库中都是安全的。
databases supported by Django.
 
  
It uses [[../../validators#django.core.validators|<code>MinValueValidator</code>]] and
+
它使用 [[../../validators#django.core.validators|MinValueValidator]] [[../../validators#django.core.validators|MaxValueValidator]] 根据默认数据库支持的值验证输入。
[[../../validators#django.core.validators|<code>MaxValueValidator</code>]] to validate the input based
 
on the values that the default database supports.
 
  
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>NumberInput</code>]]
+
[[../../forms/fields#django.forms.Field|localize]] 为 <code>False</code> [[../../forms/widgets#django.forms|TextInput]] 时,此字段的默认表单小部件为 [[../../forms/widgets#django.forms|NumberInput]]
when [[../../forms/fields#django.forms.Field|<code>localize</code>]] is <code>False</code> or
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]] otherwise.
 
  
  
第1,204行: 第948行:
 
<div id="genericipaddressfield" class="section">
 
<div id="genericipaddressfield" class="section">
  
=== <code>GenericIPAddressField</code> ===
+
=== GenericIPAddressField ===
  
; ''class'' <code>GenericIPAddressField</code><span class="sig-paren">(</span>''<span class="n">protocol</span><span class="o">=</span><span class="default_value">'both'</span>'', ''<span class="n">unpack_ipv4</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#GenericIPAddressField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">GenericIPAddressField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">protocol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'both'</span></span>'', ''<span class="n"><span class="pre">unpack_ipv4</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
An IPv4 or IPv6 address, in string format (e.g. <code>192.0.2.30</code> or
+
字符串格式的 IPv4 IPv6 地址(例如 <code>192.0.2.30</code> <code>2a02:42fe::4</code>)。 此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]
<code>2a02:42fe::4</code>). The default form widget for this field is a
 
[[../../forms/widgets#django.forms|<code>TextInput</code>]].
 
  
The IPv6 address normalization follows <span id="index-0" class="target"></span>[https://tools.ietf.org/html/rfc4291.html#section-2.2 '''RFC 4291#section-2.2'''] section 2.2,
+
IPv6 地址规范化遵循 <span id="index-0" class="target"></span>[https://tools.ietf.org/html/rfc4291.html#section-2.2 RFC 4291#section-2.2] 2.2 节,包括使用该节第 3 段中建议的 IPv4 格式,如 <code>::ffff:192.0.2.0</code>。 例如,<code>2001:0::0:01</code> 将归一化为 <code>2001::1</code>,而 <code>::ffff:0a0a:0a0a</code> 将归一化为 <code>::ffff:10.10.10.10</code>。 所有字符都转换为小写。
including using the IPv4 format suggested in paragraph 3 of that section, like
 
<code>::ffff:192.0.2.0</code>. For example, <code>2001:0::0:01</code> would be normalized to
 
<code>2001::1</code>, and <code>::ffff:0a0a:0a0a</code> to <code>::ffff:10.10.10.10</code>. All characters
 
are converted to lowercase.
 
  
; <code>GenericIPAddressField.</code><code>protocol</code>
+
; <span class="sig-prename descclassname"><span class="pre">GenericIPAddressField.</span></span><span class="sig-name descname"><span class="pre">protocol</span></span>
: Limits valid inputs to the specified protocol. Accepted values are <code>'both'</code> (default), <code>'IPv4'</code> or <code>'IPv6'</code>. Matching is case insensitive.
+
: 将有效输入限制为指定协议。 可接受的值为 <code>'both'</code>(默认)、<code>'IPv4'</code> <code>'IPv6'</code>。 匹配不区分大小写。
  
; <code>GenericIPAddressField.</code><code>unpack_ipv4</code>
+
; <span class="sig-prename descclassname"><span class="pre">GenericIPAddressField.</span></span><span class="sig-name descname"><span class="pre">unpack_ipv4</span></span>
: Unpacks IPv4 mapped addresses like <code>::ffff:192.0.2.1</code>. If this option is enabled that address would be unpacked to <code>192.0.2.1</code>. Default is disabled. Can only be used when <code>protocol</code> is set to <code>'both'</code>.
+
: 解压缩 IPv4 映射地址,如 <code>::ffff:192.0.2.1</code>。 如果启用此选项,该地址将被解压缩到 <code>192.0.2.1</code>。 默认为禁用。 仅当 <code>protocol</code> 设置为 <code>'both'</code> 时才能使用。
  
If you allow for blank values, you have to allow for null values since blank
+
如果允许空值,就必须允许 null 值,因为空值会被存储为 null。
values are stored as null.
 
  
  
第1,232行: 第969行:
 
<div id="nullbooleanfield" class="section">
 
<div id="nullbooleanfield" class="section">
  
=== <code>NullBooleanField</code> ===
+
=== NullBooleanField ===
  
; ''class'' <code>NullBooleanField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#NullBooleanField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">NullBooleanField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Like [[#django.db.models.BooleanField|<code>BooleanField</code>]] with <code>null=True</code>. Use that instead of this field
+
[[#django.db.models.BooleanField|BooleanField]] <code>null=True</code>。 使用它而不是这个字段,因为它可能会在 Django 的未来版本中被弃用。
as it's likely to be deprecated in a future version of Django.
 
  
  
第1,244行: 第980行:
 
<div id="positiveintegerfield" class="section">
 
<div id="positiveintegerfield" class="section">
  
=== <code>PositiveIntegerField</code> ===
+
=== PositiveIntegerField ===
  
; ''class'' <code>PositiveIntegerField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#PositiveIntegerField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">PositiveIntegerField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Like an [[#django.db.models.IntegerField|<code>IntegerField</code>]], but must be either positive or zero (<code>0</code>).
+
类似于 [[#django.db.models.IntegerField|IntegerField]],但必须为正数或零 (<code>0</code>)。 从 <code>0</code> <code>2147483647</code> 的值在 Django 支持的所有数据库中都是安全的。 出于向后兼容性的原因,接受值 <code>0</code>
Values from <code>0</code> to <code>2147483647</code> are safe in all databases supported by
 
Django. The value <code>0</code> is accepted for backward compatibility reasons.
 
  
  
第1,257行: 第991行:
 
<div id="positivesmallintegerfield" class="section">
 
<div id="positivesmallintegerfield" class="section">
  
=== <code>PositiveSmallIntegerField</code> ===
+
=== PositiveSmallIntegerField ===
  
; ''class'' <code>PositiveSmallIntegerField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#PositiveSmallIntegerField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">PositiveSmallIntegerField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Like a [[#django.db.models.PositiveIntegerField|<code>PositiveIntegerField</code>]], but only allows values under a certain
+
[[#django.db.models.PositiveIntegerField|PositiveIntegerField]],但只允许某个(依赖于数据库的)点下的值。 从 <code>0</code> <code>32767</code> 的值在 Django 支持的所有数据库中都是安全的。
(database-dependent) point. Values from <code>0</code> to <code>32767</code> are safe in all
 
databases supported by Django.
 
  
  
第1,270行: 第1,002行:
 
<div id="slugfield" class="section">
 
<div id="slugfield" class="section">
  
=== <code>SlugField</code> ===
+
=== SlugField ===
  
; ''class'' <code>SlugField</code><span class="sig-paren">(</span>''<span class="n">max_length</span><span class="o">=</span><span class="default_value">50</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#SlugField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">SlugField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">50</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
[[../../../glossary#term-slug|<span class="xref std std-term">Slug</span>]] is a newspaper term. A slug is a short label for something,
+
[[../../../glossary#term-slug|Slug]] 是一个报纸术语。 slug 是某物的短标签,仅包含字母、数字、下划线或连字符。 它们通常用于 URL。
containing only letters, numbers, underscores or hyphens. They're generally used
 
in URLs.
 
  
Like a CharField, you can specify [[#django.db.models.CharField.max_length|<code>max_length</code>]] (read the note
+
CharField 一样,您可以指定 [[#django.db.models.CharField.max_length|max_length]](也请阅读该部分中有关数据库可移植性和 [[#django.db.models.CharField.max_length|max_length]] 的说明)。 如果未指定 [[#django.db.models.CharField.max_length|max_length]],Django 将使用默认长度 50。
about database portability and [[#django.db.models.CharField.max_length|<code>max_length</code>]] in that section,
 
too). If [[#django.db.models.CharField.max_length|<code>max_length</code>]] is not specified, Django will use a
 
default length of 50.
 
  
Implies setting [[#django.db.models.Field.db_index|<code>Field.db_index</code>]] to <code>True</code>.
+
意味着将 [[#django.db.models.Field.db_index|Field.db_index]] 设置为 <code>True</code>
  
It is often useful to automatically prepopulate a SlugField based on the value
+
根据某些其他值的值自动预填充 SlugField 通常很有用。 您可以使用 [[../../contrib/admin/index#django.contrib.admin.ModelAdmin|prepopulated_fields]] 在管理员中自动执行此操作。
of some other value. You can do this automatically in the admin using
 
[[../../contrib/admin/index#django.contrib.admin.ModelAdmin|<code>prepopulated_fields</code>]].
 
  
It uses [[../../validators#django.core.validators|<code>validate_slug</code>]] or
+
它使用 [[../../validators#django.core.validators|validate_slug]] [[../../validators#django.core.validators|validate_unicode_slug]] 进行验证。
[[../../validators#django.core.validators|<code>validate_unicode_slug</code>]] for validation.
 
  
; <code>SlugField.</code><code>allow_unicode</code>
+
; <span class="sig-prename descclassname"><span class="pre">SlugField.</span></span><span class="sig-name descname"><span class="pre">allow_unicode</span></span>
: If <code>True</code>, the field accepts Unicode letters in addition to ASCII letters. Defaults to <code>False</code>.
+
: 如果是 <code>True</code>,则该字段除 ASCII 字母外还接受 Unicode 字母。 默认为 <code>False</code>
  
  
第1,300行: 第1,024行:
 
<div id="smallintegerfield" class="section">
 
<div id="smallintegerfield" class="section">
  
=== <code>SmallIntegerField</code> ===
+
=== SmallIntegerField ===
  
; ''class'' <code>SmallIntegerField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#SmallIntegerField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">SmallIntegerField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Like an [[#django.db.models.IntegerField|<code>IntegerField</code>]], but only allows values under a certain
+
类似于 [[#django.db.models.IntegerField|IntegerField]],但只允许某个(依赖于数据库的)点下的值。 从 <code>-32768</code> <code>32767</code> 的值在 Django 支持的所有数据库中都是安全的。
(database-dependent) point. Values from <code>-32768</code> to <code>32767</code> are safe in all
 
databases supported by Django.
 
  
  
第1,313行: 第1,035行:
 
<div id="textfield" class="section">
 
<div id="textfield" class="section">
  
=== <code>TextField</code> ===
+
=== TextField ===
  
; ''class'' <code>TextField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#TextField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">TextField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A large text field. The default form widget for this field is a
+
一个大文本字段。 此字段的默认表单小部件是 [[../../forms/widgets#django.forms|Textarea]]
[[../../forms/widgets#django.forms|<code>Textarea</code>]].
 
  
If you specify a <code>max_length</code> attribute, it will be reflected in the
+
如果您指定 <code>max_length</code> 属性,它将反映在自动生成的表单字段的 [[../../forms/widgets#django.forms|Textarea]] 小部件中。 但是,它不会在模型或数据库级别强制执行。 为此使用 [[#django.db.models.CharField|CharField]]
[[../../forms/widgets#django.forms|<code>Textarea</code>]] widget of the auto-generated form field.
 
However it is not enforced at the model or database level. Use a
 
[[#django.db.models.CharField|<code>CharField</code>]] for that.
 
  
  
第1,330行: 第1,048行:
 
<div id="timefield" class="section">
 
<div id="timefield" class="section">
  
=== <code>TimeField</code> ===
+
=== TimeField ===
  
; ''class'' <code>TimeField</code><span class="sig-paren">(</span>''<span class="n">auto_now</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">auto_now_add</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#TimeField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">TimeField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">auto_now</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">auto_now_add</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A time, represented in Python by a <code>datetime.time</code> instance. Accepts the same
+
时间,在 Python 中由 <code>datetime.time</code> 实例表示。 接受与 [[#django.db.models.DateField|DateField]] 相同的自动填充选项。
auto-population options as [[#django.db.models.DateField|<code>DateField</code>]].
 
  
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>TextInput</code>]].
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]。 管理员添加了一些 JavaScript 快捷方式。
The admin adds some JavaScript shortcuts.
 
  
  
第1,345行: 第1,061行:
 
<div id="urlfield" class="section">
 
<div id="urlfield" class="section">
  
=== <code>URLField</code> ===
+
=== URLField ===
  
; ''class'' <code>URLField</code><span class="sig-paren">(</span>''<span class="n">max_length</span><span class="o">=</span><span class="default_value">200</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#URLField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">URLField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">200</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A [[#django.db.models.CharField|<code>CharField</code>]] for a URL, validated by
+
URL 的 [[#django.db.models.CharField|CharField]],由 [[../../validators#django.core.validators|URLValidator]] 验证。
[[../../validators#django.core.validators|<code>URLValidator</code>]].
 
  
The default form widget for this field is a [[../../forms/widgets#django.forms|<code>TextInput</code>]].
+
此字段的默认表单小部件是 [[../../forms/widgets#django.forms|TextInput]]
  
Like all [[#django.db.models.CharField|<code>CharField</code>]] subclasses, [[#django.db.models.URLField|<code>URLField</code>]] takes the optional
+
与所有 [[#django.db.models.CharField|CharField]] 子类一样,[[#django.db.models.URLField|URLField]] 采用可选的 [[#django.db.models.CharField.max_length|max_length]] 参数。 如果未指定 [[#django.db.models.CharField.max_length|max_length]],则使用默认值 200。
[[#django.db.models.CharField.max_length|<code>max_length</code>]] argument. If you don't specify
 
[[#django.db.models.CharField.max_length|<code>max_length</code>]], a default of 200 is used.
 
  
  
第1,363行: 第1,076行:
 
<div id="uuidfield" class="section">
 
<div id="uuidfield" class="section">
  
=== <code>UUIDField</code> ===
+
=== UUIDField ===
  
; ''class'' <code>UUIDField</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#UUIDField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">UUIDField</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A field for storing universally unique identifiers. Uses Python's
+
用于存储通用唯一标识符的字段。 使用 Python <code>UUID</code> 类。 在 PostgreSQL 上使用时,它存储在 <code>uuid</code> 数据类型中,否则存储在 <code>char(32)</code> 中。
<code>UUID</code> class. When used on PostgreSQL, this stores in a
 
<code>uuid</code> datatype, otherwise in a <code>char(32)</code>.
 
  
Universally unique identifiers are a good alternative to [[#django.db.models.AutoField|<code>AutoField</code>]] for
+
对于 [[#django.db.models.Field.primary_key|primary_key]],通用唯一标识符是 [[#django.db.models.AutoField|AutoField]] 的一个很好的替代方案。 数据库不会为你生成UUID,所以建议使用[[#django.db.models.Field.default|default]]
[[#django.db.models.Field.primary_key|<code>primary_key</code>]]. The database will not generate the UUID for you, so
 
it is recommended to use [[#django.db.models.Field.default|<code>default</code>]]:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,380行: 第1,089行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import uuid
+
<syntaxhighlight lang="python">import uuid
 
from django.db import models
 
from django.db import models
  
 
class MyUUIDModel(models.Model):
 
class MyUUIDModel(models.Model):
 
     id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
 
     id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
     # other fields</pre>
+
     # other fields</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that a callable (with the parentheses omitted) is passed to <code>default</code>,
+
请注意,一个可调用对象(省略括号)被传递给 <code>default</code>,而不是 <code>UUID</code> 的实例。
not an instance of <code>UUID</code>.
 
  
 
<div class="admonition-lookups-on-postgresql admonition">
 
<div class="admonition-lookups-on-postgresql admonition">
  
Lookups on PostgreSQL
+
PostgreSQL 上查找
  
Using [[../querysets#std-fieldlookup-iexact|<code>iexact</code>]], [[../querysets#std-fieldlookup-contains|<code>contains</code>]], [[../querysets#std-fieldlookup-icontains|<code>icontains</code>]],
+
使用 [[#id17|:lookup:`iexact`]], [[#id19|:lookup:`contains`]], [[#id21|:lookup:`icontains`]], :lookup:`startswith`[ X116X][[#id25|:lookup:`istartswith`]][[#id27|:lookup:`endswith`]] [[#id29|:lookup:`iendswith`]] PostgreSQL 上的查找不起作用没有连字符的值,因为 PostgreSQL 将它们存储在带连字符的 uuid 数据类型中。
[[../querysets#std-fieldlookup-startswith|<code>startswith</code>]], [[../querysets#std-fieldlookup-istartswith|<code>istartswith</code>]], [[../querysets#std-fieldlookup-endswith|<code>endswith</code>]], or
 
[[../querysets#std-fieldlookup-iendswith|<code>iendswith</code>]] lookups on PostgreSQL don't work for values without
 
hyphens, because PostgreSQL stores them in a hyphenated uuid datatype type.
 
  
  
第1,411行: 第1,116行:
  
 
<span id="relationship-fields"></span>
 
<span id="relationship-fields"></span>
== 关联关系字段 ==
+
== 关系字段 ==
  
Django也定义了一组代表关系的字段。
+
Django 还定义了一组表示关系的字段。
  
 
<div id="foreignkey" class="section">
 
<div id="foreignkey" class="section">
  
 
<span id="ref-foreignkey"></span>
 
<span id="ref-foreignkey"></span>
=== <code>ForeignKey</code> ===
+
=== ForeignKey ===
  
; ''class'' <code>ForeignKey</code><span class="sig-paren">(</span>''<span class="n">to</span>'', ''<span class="n">on_delete</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/related.html#ForeignKey|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ForeignKey</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">to</span></span>'', ''<span class="n"><span class="pre">on_delete</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
多对一的关系。需要两个位置参数:被关联的类和 [[#django.db.models.ForeignKey.on_delete|<code>on_delete</code>]] 选项
+
多对一的关系。 需要两个位置参数:与模型相关的类和 [[#django.db.models.ForeignKey.on_delete|on_delete]] 选项。
  
如果要创建一个递归关系 -- 一个与其自身有多对一关系的对象 -- 则使用 <code>models.ForeignKey('self', on_delete=models.CASCADE)</code>。
+
要创建递归关系——一个与自身具有多对一关系的对象——使用 <code>models.ForeignKey('self', on_delete=models.CASCADE)</code>。
  
If you need to create a relationship on a model that has not yet been defined,
+
如果需要在尚未定义的模型上创建关系,可以使用模型的名称,而不是模型对象本身:
you can use the name of the model, rather than the model object itself:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,434行: 第1,138行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
  
 
class Car(models.Model):
 
class Car(models.Model):
第1,445行: 第1,149行:
 
class Manufacturer(models.Model):
 
class Manufacturer(models.Model):
 
     # ...
 
     # ...
     pass</pre>
+
     pass</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Relationships defined this way on [[../../../topics/db/models#abstract-base-classes|<span class="std std-ref">abstract models</span>]] are resolved when the model is subclassed as a
+
当模型被子类化为具体模型并且与抽象模型的 <code>app_label</code> 无关时,在 [[../../../topics/db/models#abstract-base-classes|抽象模型]] 上以这种方式定义的关系会得到解析:
concrete model and are not relative to the abstract model's <code>app_label</code>:
 
  
<div id="id3" class="literal-block-wrapper docutils container">
+
<div id="id35" class="literal-block-wrapper docutils container">
  
 
<div class="code-block-caption">
 
<div class="code-block-caption">
第1,464行: 第1,167行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
  
 
class AbstractCar(models.Model):
 
class AbstractCar(models.Model):
第1,470行: 第1,173行:
  
 
     class Meta:
 
     class Meta:
         abstract = True</pre>
+
         abstract = True</syntaxhighlight>
  
 
</div>
 
</div>
第1,477行: 第1,180行:
  
 
</div>
 
</div>
<div id="id4" class="literal-block-wrapper docutils container">
+
<div id="id36" class="literal-block-wrapper docutils container">
  
 
<div class="code-block-caption">
 
<div class="code-block-caption">
第1,488行: 第1,191行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
 
from products.models import AbstractCar
 
from products.models import AbstractCar
  
第1,497行: 第1,200行:
 
     pass
 
     pass
  
# Car.manufacturer will point to `production.Manufacturer` here.</pre>
+
# Car.manufacturer will point to `production.Manufacturer` here.</syntaxhighlight>
  
 
</div>
 
</div>
第1,504行: 第1,207行:
  
 
</div>
 
</div>
To refer to models defined in another application, you can explicitly specify
+
要引用在另一个应用程序中定义的模型,您可以明确指定具有完整应用程序标签的模型。 例如,如果上面的 <code>Manufacturer</code> 模型是在另一个名为 <code>production</code> 的应用程序中定义的,则您需要使用:
a model with the full application label. For example, if the <code>Manufacturer</code>
 
model above is defined in another application called <code>production</code>, you'd
 
need to use:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,513行: 第1,213行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class Car(models.Model):
+
<syntaxhighlight lang="python">class Car(models.Model):
 
     manufacturer = models.ForeignKey(
 
     manufacturer = models.ForeignKey(
 
         'production.Manufacturer',
 
         'production.Manufacturer',
 
         on_delete=models.CASCADE,
 
         on_delete=models.CASCADE,
     )</pre>
+
     )</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
This sort of reference, called a lazy relationship, can be useful when
+
这种被称为懒惰关系的引用,在解决两个应用程序之间的循环导入依赖关系时很有用。
resolving circular import dependencies between two applications.
 
  
A database index is automatically created on the <code>ForeignKey</code>. You can
+
<code>ForeignKey</code> 上自动创建数据库索引。 您可以通过将 [[#django.db.models.Field.db_index|db_index]] 设置为 <code>False</code> 来禁用此功能。 如果您创建外键是为了一致性而不是连接,或者您将创建替代索引(如部分或多列索引),您可能希望避免索引的开销。
disable this by setting [[#django.db.models.Field.db_index|<code>db_index</code>]] to <code>False</code>. You may want to
 
avoid the overhead of an index if you are creating a foreign key for
 
consistency rather than joins, or if you will be creating an alternative index
 
like a partial or multiple column index.
 
  
 
<div id="database-representation" class="section">
 
<div id="database-representation" class="section">
第1,535行: 第1,230行:
 
==== 数据库表现 ====
 
==== 数据库表现 ====
  
Behind the scenes, Django appends <code>&quot;_id&quot;</code> to the field name to create its
+
在幕后,Django 将 <code>&quot;_id&quot;</code> 附加到字段名称以创建其数据库列名称。 在上面的例子中,<code>Car</code> 模型的数据库表将有一个 <code>manufacturer_id</code> 列。 (您可以通过指定 [[#django.db.models.Field.db_column|db_column]] 来显式更改此设置)但是,除非您编写自定义 SQL,否则您的代码永远不必处理数据库列名。 您将始终处理模型对象的字段名称。
database column name. In the above example, the database table for the <code>Car</code>
 
model will have a <code>manufacturer_id</code> column. (You can change this explicitly by
 
specifying [[#django.db.models.Field.db_column|<code>db_column</code>]]) However, your code should never have to
 
deal with the database column name, unless you write custom SQL. You'll always
 
deal with the field names of your model object.
 
  
  
第1,549行: 第1,239行:
 
==== 参数 ====
 
==== 参数 ====
  
[[#django.db.models.ForeignKey|<code>ForeignKey</code>]] accepts other arguments that define the details of how the
+
[[#django.db.models.ForeignKey|ForeignKey]] 接受定义关系如何工作的细节的其他参数。
relation works.
 
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>on_delete</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">on_delete</span></span></dt>
<dd><p>When an object referenced by a [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] is deleted, Django will
+
<dd><p>[[#django.db.models.ForeignKey|ForeignKey]] 引用的对象被删除时,Django 将模拟由 [[#django.db.models.ForeignKey.on_delete|on_delete]] 参数指定的 SQL 约束的行为。 例如,如果您有一个可以为 null 的 [[#django.db.models.ForeignKey|ForeignKey]] 并且您希望在删除引用的对象时将其设置为 null:</p>
emulate the behavior of the SQL constraint specified by the
 
[[#django.db.models.ForeignKey.on_delete|<code>on_delete</code>]] argument. For example, if you have a nullable
 
[[#django.db.models.ForeignKey|<code>ForeignKey</code>]] and you want it to be set null when the referenced
 
object is deleted:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>user = models.ForeignKey(
+
<syntaxhighlight lang="python">user = models.ForeignKey(
 
     User,
 
     User,
 
     models.SET_NULL,
 
     models.SET_NULL,
 
     blank=True,
 
     blank=True,
 
     null=True,
 
     null=True,
)</pre>
+
)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p><code>on_delete</code> doesn't create a SQL constraint in the database. Support for
+
<p><code>on_delete</code> 不会在数据库中创建 SQL 约束。 支持数据库级级联选项 [[#id31|:ticket:`可能会在以后实施 &lt;21961&gt;`]] .</p></dd></dl>
database-level cascade options [https://code.djangoproject.com/ticket/21961 may be implemented later].</p></dd></dl>
 
  
The possible values for [[#django.db.models.ForeignKey.on_delete|<code>on_delete</code>]] are found in
+
[[#django.db.models.ForeignKey.on_delete|on_delete]] 的可能值在 [[../../../topics/db/models#module-django.db|django.db.models]] 中找到:
[[../../../topics/db/models#module-django.db|<code>django.db.models</code>]]:
 
  
 
<ul>
 
<ul>
 
<li><dl>
 
<li><dl>
<dt><code>CASCADE</code>[[../../_modules/django/db/models/deletion.html#CASCADE|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">CASCADE</span></span></dt>
<dd><p>Cascade deletes. Django emulates the behavior of the SQL constraint ON
+
<dd><p>级联删除。 Django 模拟 SQL 约束 ON DELETE CASCADE 的行为,并删除包含 ForeignKey 的对象。</p>
DELETE CASCADE and also deletes the object containing the ForeignKey.</p>
+
<p>[[../instances#django.db.models.Model|Model.delete()]] 不会在相关模型上调用,但会为所有已删除的对象发送 [[../../signals#django.db.models.signals|pre_delete]] [[../../signals#django.db.models.signals|post_delete]] 信号。</p></dd></dl>
<p>[[../instances#django.db.models.Model|<code>Model.delete()</code>]] isn't called on related models, but the
 
[[../../signals#django.db.models.signals|<code>pre_delete</code>]] and
 
[[../../signals#django.db.models.signals|<code>post_delete</code>]] signals are sent for all
 
deleted objects.</p></dd></dl>
 
 
</li>
 
</li>
 
<li><dl>
 
<li><dl>
<dt><code>PROTECT</code>[[../../_modules/django/db/models/deletion.html#PROTECT|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">PROTECT</span></span></dt>
<dd><p>Prevent deletion of the referenced object by raising
+
<dd><p>通过引发 [[../../exceptions#django.db.models|ProtectedError]][[../../exceptions#django.db|django.db.IntegrityError]] 的子类)来防止删除引用的对象。</p></dd></dl>
[[../../exceptions#django.db.models|<code>ProtectedError</code>]], a subclass of
 
[[../../exceptions#django.db|<code>django.db.IntegrityError</code>]].</p></dd></dl>
 
 
</li>
 
</li>
 
<li><dl>
 
<li><dl>
<dt><code>SET_NULL</code>[[../../_modules/django/db/models/deletion.html#SET_NULL|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">SET_NULL</span></span></dt>
<dd><p>Set the [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] null; this is only possible if
+
<dd><p>设置 [[#django.db.models.ForeignKey|ForeignKey]] 为空; 这仅在 [[#django.db.models.Field.null|null]] <code>True</code> 时才有可能。</p></dd></dl>
[[#django.db.models.Field.null|<code>null</code>]] is <code>True</code>.</p></dd></dl>
 
 
</li>
 
</li>
 
<li><dl>
 
<li><dl>
<dt><code>SET_DEFAULT</code>[[../../_modules/django/db/models/deletion.html#SET_DEFAULT|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">SET_DEFAULT</span></span></dt>
<dd><p>Set the [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] to its default value; a default for the
+
<dd><p>[[#django.db.models.ForeignKey|ForeignKey]] 设置为其默认值; 必须设置 [[#django.db.models.ForeignKey|ForeignKey]] 的默认值。</p></dd></dl>
[[#django.db.models.ForeignKey|<code>ForeignKey</code>]] must be set.</p></dd></dl>
 
 
</li>
 
</li>
 
<li><dl>
 
<li><dl>
<dt><code>SET</code><span class="sig-paren">(</span><span class="sig-paren">)</span>[[../../_modules/django/db/models/deletion.html#SET|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">SET</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Set the [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] to the value passed to
+
<dd><p>[[#django.db.models.ForeignKey|ForeignKey]] 设置为传递给 [[#django.db.models.SET|SET()]] 的值,或者如果传入的是 callable,则为调用它的结果。 在大多数情况下,需要传递一个可调用对象以避免在导入 models.py 时执行查询:</p>
[[#django.db.models.SET|<code>SET()</code>]], or if a callable is passed in,
 
the result of calling it. In most cases, passing a callable will be
 
necessary to avoid executing queries at the time your models.py is
 
imported:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.conf import settings
+
<syntaxhighlight lang="python">from django.conf import settings
 
from django.contrib.auth import get_user_model
 
from django.contrib.auth import get_user_model
 
from django.db import models
 
from django.db import models
第1,627行: 第1,298行:
 
         settings.AUTH_USER_MODEL,
 
         settings.AUTH_USER_MODEL,
 
         on_delete=models.SET(get_sentinel_user),
 
         on_delete=models.SET(get_sentinel_user),
     )</pre>
+
     )</syntaxhighlight>
  
 
</div>
 
</div>
第1,634行: 第1,305行:
 
</li>
 
</li>
 
<li><dl>
 
<li><dl>
<dt><code>DO_NOTHING</code>[[../../_modules/django/db/models/deletion.html#DO_NOTHING|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">DO_NOTHING</span></span></dt>
<dd><p>Take no action. If your database backend enforces referential
+
<dd><p>不采取行动。 如果您的数据库后端强制执行参照完整性,除非您手动向数据库字段添加 SQL <code>ON DELETE</code> 约束,否则这将导致 [[../../exceptions#django.db|IntegrityError]]</p></dd></dl>
integrity, this will cause an [[../../exceptions#django.db|<code>IntegrityError</code>]] unless
 
you manually add an SQL <code>ON DELETE</code> constraint to the database field.</p></dd></dl>
 
 
</li></ul>
 
</li></ul>
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>limit_choices_to</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">limit_choices_to</span></span></dt>
<dd><p>Sets a limit to the available choices for this field when this field is
+
<dd><p>当使用 <code>ModelForm</code> 或管理员呈现此字段时,为该字段的可用选项设置限制(默认情况下,查询集中的所有对象都可供选择)。 可以使用字典、[[../querysets#django.db.models|Q]] 对象或返回字典或 [[../querysets#django.db.models|Q]] 对象的可调用对象。</p>
rendered using a <code>ModelForm</code> or the admin (by default, all objects
+
<p>例如:</p>
in the queryset are available to choose). Either a dictionary, a
 
[[../querysets#django.db.models|<code>Q</code>]] object, or a callable returning a
 
dictionary or [[../querysets#django.db.models|<code>Q</code>]] object can be used.</p>
 
<p>例子:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>staff_member = models.ForeignKey(
+
<syntaxhighlight lang="python">staff_member = models.ForeignKey(
 
     User,
 
     User,
 
     on_delete=models.CASCADE,
 
     on_delete=models.CASCADE,
 
     limit_choices_to={'is_staff': True},
 
     limit_choices_to={'is_staff': True},
)</pre>
+
)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>causes the corresponding field on the <code>ModelForm</code> to list only <code>Users</code>
+
<p>导致 <code>ModelForm</code> 上的相应字段仅列出具有 <code>is_staff=True</code> <code>Users</code>。 这可能对 Django 管理员有所帮助。</p>
that have <code>is_staff=True</code>. This may be helpful in the Django admin.</p>
+
<p>例如,当与 Python <code>datetime</code> 模块结合使用以按日期范围限制选择时,可调用表单会很有帮助。 例如:</p>
<p>The callable form can be helpful, for instance, when used in conjunction
 
with the Python <code>datetime</code> module to limit selections by date range. For
 
example:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def limit_pub_date_choices():
+
<syntaxhighlight lang="python">def limit_pub_date_choices():
 
     return {'pub_date__lte': datetime.date.utcnow()}
 
     return {'pub_date__lte': datetime.date.utcnow()}
  
limit_choices_to = limit_pub_date_choices</pre>
+
limit_choices_to = limit_pub_date_choices</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If <code>limit_choices_to</code> is or returns a [[../querysets#django.db.models|<code>Q object</code>]], which is useful for [[../../../topics/db/queries#complex-lookups-with-q|<span class="std std-ref">complex queries</span>]], then it will only have an effect on the choices
+
<p>如果 <code>limit_choices_to</code> 是或返回一个 [[../querysets#django.db.models|Q 对象]] ,这对 [[../../../topics/db/queries#complex-lookups-with-q|复杂查询]] 很有用,那么它只会影响 admin 中可用的选项未在该模型的 <code>ModelAdmin</code> 中的 [[../../contrib/admin/index#django.contrib.admin.ModelAdmin|raw_id_fields]] 中列出。</p>
available in the admin when the field is not listed in
 
[[../../contrib/admin/index#django.contrib.admin.ModelAdmin|<code>raw_id_fields</code>]] in the
 
<code>ModelAdmin</code> for the model.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>If a callable is used for <code>limit_choices_to</code>, it will be invoked
+
<p>如果可调用对象用于 <code>limit_choices_to</code>,则每次实例化新表单时都会调用它。 它也可以在模型被验证时调用,例如通过管理命令或管理员。 管理员构建查询集以在各种边缘情况下多次验证其表单输入,因此您的可调用对象可能会被多次调用。</p>
every time a new form is instantiated. It may also be invoked when a
 
model is validated, for example by management commands or the admin.
 
The admin constructs querysets to validate its form inputs in various
 
edge cases multiple times, so there is a possibility your callable may
 
be invoked several times.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>related_name</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">related_name</span></span></dt>
<dd><p>The name to use for the relation from the related object back to this one.
+
<dd><p>用于从相关对象返回到此对象的关系的名称。 它也是 [[#django.db.models.ForeignKey.related_query_name|related_query_name]](用于来自目标模型的反向过滤器名称的名称)的默认值。 有关完整说明和示例,请参阅 [[../../../topics/db/queries#backwards-related-objects|相关对象文档]] 。 注意在[[../../../topics/db/models#abstract-base-classes|抽象模型]]上定义关系时必须设置这个值; 当你这样做时 [[../../../topics/db/models#abstract-related-name|一些特殊的语法]] 可用。</p>
It's also the default value for [[#django.db.models.ForeignKey.related_query_name|<code>related_query_name</code>]] (the name to use
+
<p>如果您不希望 Django 创建反向关系,请将 <code>related_name</code> 设置为 <code>'+'</code> 或以 <code>'+'</code> 结束。 例如,这将确保 <code>User</code> 模型不会与此模型具有向后关系:</p>
for the reverse filter name from the target model). See the [[../../../topics/db/queries#backwards-related-objects|<span class="std std-ref">related
 
objects documentation</span>]] for a full explanation
 
and example. Note that you must set this value when defining relations on
 
[[../../../topics/db/models#abstract-base-classes|<span class="std std-ref">abstract models</span>]]; and when you do so
 
[[../../../topics/db/models#abstract-related-name|<span class="std std-ref">some special syntax</span>]] is available.</p>
 
<p>If you'd prefer Django not to create a backwards relation, set
 
<code>related_name</code> to <code>'+'</code> or end it with <code>'+'</code>. For example, this will
 
ensure that the <code>User</code> model won't have a backwards relation to this
 
model:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>user = models.ForeignKey(
+
<syntaxhighlight lang="python">user = models.ForeignKey(
 
     User,
 
     User,
 
     on_delete=models.CASCADE,
 
     on_delete=models.CASCADE,
 
     related_name='+',
 
     related_name='+',
)</pre>
+
)</syntaxhighlight>
  
 
</div>
 
</div>
第1,722行: 第1,367行:
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>related_query_name</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">related_query_name</span></span></dt>
<dd><p>The name to use for the reverse filter name from the target model. It
+
<dd><p>用于来自目标模型的反向过滤器名称的名称。 如果设置,则默认为 [[#django.db.models.ForeignKey.related_name|related_name]] [[../options#django.db.models.Options|default_related_name]] 的值,否则默认为模型名称:</p>
defaults to the value of [[#django.db.models.ForeignKey.related_name|<code>related_name</code>]] or
 
[[../options#django.db.models.Options|<code>default_related_name</code>]] if set, otherwise it
 
defaults to the name of the model:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre># Declare the ForeignKey with related_query_name
+
<syntaxhighlight lang="python"># Declare the ForeignKey with related_query_name
 
class Tag(models.Model):
 
class Tag(models.Model):
 
     article = models.ForeignKey(
 
     article = models.ForeignKey(
 
         Article,
 
         Article,
 
         on_delete=models.CASCADE,
 
         on_delete=models.CASCADE,
         related_name=&quot;tags&quot;,
+
         related_name="tags",
         related_query_name=&quot;tag&quot;,
+
         related_query_name="tag",
 
     )
 
     )
 
     name = models.CharField(max_length=255)
 
     name = models.CharField(max_length=255)
  
 
# That's now the name of the reverse filter
 
# That's now the name of the reverse filter
Article.objects.filter(tag__name=&quot;important&quot;)</pre>
+
Article.objects.filter(tag__name="important")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Like [[#django.db.models.ForeignKey.related_name|<code>related_name</code>]], <code>related_query_name</code> supports app label and
+
<p>[[#django.db.models.ForeignKey.related_name|related_name]]一样,<code>related_query_name</code>通过[[../../../topics/db/models#abstract-related-name|一些特殊语法]]支持应用标签和类插值。</p></dd></dl>
class interpolation via [[../../../topics/db/models#abstract-related-name|<span class="std std-ref">some special syntax</span>]].</p></dd></dl>
 
  
; <code>ForeignKey.</code><code>to_field</code>
+
; <span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">to_field</span></span>
: The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have <code>unique=True</code>.
+
: 关系所指向的相关对象上的字段。 默认情况下,Django 使用相关对象的主键。 如果您引用不同的字段,则该字段必须具有 <code>unique=True</code>
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>db_constraint</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">db_constraint</span></span></dt>
<dd><p>控制是否中介模型中外键的约束应该在数据库中被创建。默认值是``True``, 而且这几乎确定就是你需要的功能。将这个设为False会损坏数据的完整性。即便如此,一下场景一可能需要这样做</p>
+
<dd><p>控制是否应在数据库中为此外键创建约束。 默认值为 <code>True</code>,这几乎肯定是您想要的; 将此设置为 <code>False</code> 可能对数据完整性非常不利。 也就是说,以下是您可能想要执行此操作的一些场景:</p>
 
<ul>
 
<ul>
 
<li><p>你有无效的冗余数据</p></li>
 
<li><p>你有无效的冗余数据</p></li>
<li><p>你正在共享你的数据库</p></li></ul>
+
<li><p>您正在对数据库进行分片。</p></li></ul>
  
<p>If this is set to <code>False</code>, accessing a related object that doesn't exist
+
<p>如果将其设置为 <code>False</code>,则访问不存在的相关对象将引发其 <code>DoesNotExist</code> 异常。</p></dd></dl>
will raise its <code>DoesNotExist</code> exception.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>ForeignKey.</code><code>swappable</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ForeignKey.</span></span><span class="sig-name descname"><span class="pre">swappable</span></span></dt>
<dd><p>Controls the migration framework's reaction if this [[#django.db.models.ForeignKey|<code>ForeignKey</code>]]
+
<dd><p>如果此 [[#django.db.models.ForeignKey|ForeignKey]] 指向可交换模型,则控制迁移框架的反应。 如果它是 <code>True</code> - 默认值 - 那么如果 [[#django.db.models.ForeignKey|ForeignKey]] 指向与 <code>settings.AUTH_USER_MODEL</code>(或其他可交换模型设置)的当前值匹配的模型,则关系将使用对设置的引用而不是直接对模型的引用存储在迁移中。</p>
is pointing at a swappable model. If it is <code>True</code> - the default -
+
<p>如果您确定您的模型应始终指向换入模型,您只想将其覆盖为 <code>False</code> - 例如,如果它是专为您的自定义用户模型设计的配置文件模型。</p>
then if the [[#django.db.models.ForeignKey|<code>ForeignKey</code>]] is pointing at a model which matches
+
<p>将其设置为 <code>False</code> 并不意味着您可以引用可交换模型,即使它被换出 - <code>False</code> 只是意味着使用此 ForeignKey 进行的迁移将始终引用您指定的确切模型(因此例如,如果用户尝试使用您不支持的 User 模型运行,它将很难失败)。</p>
the current value of <code>settings.AUTH_USER_MODEL</code> (or another swappable
+
<p>如果有疑问,请将其保留为默认值 <code>True</code>。</p></dd></dl>
model setting) the relationship will be stored in the migration using
 
a reference to the setting, not to the model directly.</p>
 
<p>You only want to override this to be <code>False</code> if you are sure your
 
model should always point towards the swapped-in model - for example,
 
if it is a profile model designed specifically for your custom user model.</p>
 
<p>Setting it to <code>False</code> does not mean you can reference a swappable model
 
even if it is swapped out - <code>False</code> just means that the migrations made
 
with this ForeignKey will always reference the exact model you specify
 
(so it will fail hard if the user tries to run with a User model you don't
 
support, for example).</p>
 
<p>如果不确定,就保留它在默认为``True``的状态。</p></dd></dl>
 
  
  
第1,787行: 第1,416行:
 
<div id="manytomanyfield" class="section">
 
<div id="manytomanyfield" class="section">
  
=== <code>ManyToManyField</code> ===
+
=== ManyToManyField ===
  
; ''class'' <code>ManyToManyField</code><span class="sig-paren">(</span>''<span class="n">to</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/related.html#ManyToManyField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ManyToManyField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">to</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A many-to-many relationship. Requires a positional argument: the class to
+
多对多的关系。 需要一个位置参数:与模型相关的类,其工作方式与 [[#django.db.models.ForeignKey|ForeignKey]] 完全相同,包括 [[#recursive-relationships|recursive]] [[#lazy-relationships|lazy]] 关系。
which the model is related, which works exactly the same as it does for
 
[[#django.db.models.ForeignKey|<code>ForeignKey</code>]], including [[#recursive-relationships|<span class="std std-ref">recursive</span>]] and
 
[[#lazy-relationships|<span class="std std-ref">lazy</span>]] relationships.
 
  
通过这个字段的:class:~django.db.models.fields.related.RelatedManager,关联的对象可以被添加,删除,或者创建。
+
可以使用字段的 [[../relations#django.db.models.fields.related|RelatedManager]] 添加、删除或创建相关对象。
  
<div id="id1" class="section">
+
<div id="id33" class="section">
  
 
==== 数据库表现 ====
 
==== 数据库表现 ====
  
Behind the scenes, Django creates an intermediary join table to represent the
+
在幕后,Django 创建了一个中间连接表来表示多对多关系。 默认情况下,此表名称是使用多对多字段的名称和包含它的模型的表名称生成的。 由于某些数据库不支持超过一定长度的表名,这些表名将被自动截断并使用唯一性哈希,例如 <code>author_books_9cdf</code>。 您可以使用 [[#django.db.models.ManyToManyField.db_table|db_table]] 选项手动提供连接表的名称。
many-to-many relationship. By default, this table name is generated using the
 
name of the many-to-many field and the name of the table for the model that
 
contains it. Since some databases don't support table names above a certain
 
length, these table names will be automatically truncated and a uniqueness hash
 
will be used, e.g. <code>author_books_9cdf</code>. You can manually provide the name of
 
the join table using the [[#django.db.models.ManyToManyField.db_table|<code>db_table</code>]] option.
 
  
  
第1,815行: 第1,435行:
 
<div id="manytomany-arguments" class="section">
 
<div id="manytomany-arguments" class="section">
  
<span id="id2"></span>
+
<span id="id34"></span>
 
==== 参数 ====
 
==== 参数 ====
  
[[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]] accepts an extra set of arguments -- all optional --
+
[[#django.db.models.ManyToManyField|ManyToManyField]] 接受一组额外的参数——都是可选的——控制关系如何运作。
that control how the relationship functions.
 
  
; <code>ManyToManyField.</code><code>related_name</code>
+
; <span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">related_name</span></span>
: Same as [[#django.db.models.ForeignKey.related_name|<code>ForeignKey.related_name</code>]].
+
: [[#django.db.models.ForeignKey.related_name|ForeignKey.related_name]] 相同。
  
; <code>ManyToManyField.</code><code>related_query_name</code>
+
; <span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">related_query_name</span></span>
: Same as [[#django.db.models.ForeignKey.related_query_name|<code>ForeignKey.related_query_name</code>]].
+
: [[#django.db.models.ForeignKey.related_query_name|ForeignKey.related_query_name]] 相同。
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>limit_choices_to</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">limit_choices_to</span></span></dt>
<dd><p>Same as [[#django.db.models.ForeignKey.limit_choices_to|<code>ForeignKey.limit_choices_to</code>]].</p>
+
<dd><p>[[#django.db.models.ForeignKey.limit_choices_to|ForeignKey.limit_choices_to]] 相同。</p>
<p><code>limit_choices_to</code> has no effect when used on a <code>ManyToManyField</code> with a
+
<p><code>limit_choices_to</code> 在使用 [[#django.db.models.ManyToManyField.through|到]] 参数指定的自定义中间表的 <code>ManyToManyField</code> 上使用时无效。</p></dd></dl>
custom intermediate table specified using the
 
[[#django.db.models.ManyToManyField.through|<code>through</code>]] parameter.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>symmetrical</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">symmetrical</span></span></dt>
<dd><p>仅在定义自身为多对多字段关系时。考虑下面这个模型</p>
+
<dd><p>仅用于对 self 的 ManyToManyFields 的定义。 考虑以下模型:</p>
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
  
 
class Person(models.Model):
 
class Person(models.Model):
     friends = models.ManyToManyField(&quot;self&quot;)</pre>
+
     friends = models.ManyToManyField("self")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>当django处理这个模型时,它会做如此定义, 它对自身有一个:class:[[#id1|<span id="id2" class="problematic">`</span>]]ManyToManyField`的关系,并且作为结果,它没有添加一个“person_set”属性到person这个类中。而是, 这个多对多字段关系被认为是对称的——即,如果我是你的朋友,那么你也是我的朋友。</p>
+
<p>当 Django 处理这个模型时,它识别出它自己有一个 [[#django.db.models.ManyToManyField|ManyToManyField]],因此它不会向 <code>Person</code> 类添加 <code>person_set</code> 属性。 相反,假设 [[#django.db.models.ManyToManyField|ManyToManyField]] 是对称的——也就是说,如果我是你的朋友,那么你就是我的朋友。</p>
<p>If you do not want symmetry in many-to-many relationships with <code>self</code>, set
+
<p>如果您不想在与 <code>self</code> 的多对多关系中对称,请将 [[#django.db.models.ManyToManyField.symmetrical|symmetrical]] 设置为 <code>False</code>。 这将强制 Django 添加反向关系的描述符,允许 [[#django.db.models.ManyToManyField|ManyToManyField]] 关系是非对称的。</p></dd></dl>
[[#django.db.models.ManyToManyField.symmetrical|<code>symmetrical</code>]] to <code>False</code>. This will force Django to
 
add the descriptor for the reverse relationship, allowing
 
[[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]] relationships to be non-symmetrical.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>through</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">through</span></span></dt>
<dd><p>Django will automatically generate a table to manage many-to-many
+
<dd><p>Django 会自动生成一张表来管理多对多关系。 但是,如果要手动指定中间表,则可以使用 [[#django.db.models.ManyToManyField.through|]] 选项指定代表要使用的中间表的 Django 模型。</p>
relationships. However, if you want to manually specify the intermediary
+
<p>此选项最常见的用途是将 [[../../../topics/db/models#intermediary-manytomany|额外数据与多对多关系]] 相关联。</p>
table, you can use the [[#django.db.models.ManyToManyField.through|<code>through</code>]] option to specify
+
<p>如果您不指定显式 <code>through</code> 模型,仍然有一个隐式 <code>through</code> 模型类,您可以使用它直接访问为保存关联而创建的表。 它有三个字段来链接模型。</p>
the Django model that represents the intermediate table that you want to
+
<p>如果源模型和目标模型不同,则会生成以下字段:</p>
use.</p>
 
<p>The most common use for this option is when you want to associate
 
[[../../../topics/db/models#intermediary-manytomany|<span class="std std-ref">extra data with a many-to-many relationship</span>]].</p>
 
<p>If you don't specify an explicit <code>through</code> model, there is still an
 
implicit <code>through</code> model class you can use to directly access the table
 
created to hold the association. It has three fields to link the models.</p>
 
<p>如果源和目标模型不同,下面的字段会生成:</p>
 
 
<ul>
 
<ul>
<li><p><code>id</code>: the primary key of the relation.</p></li>
+
<li><p><code>id</code>:关系的主键。</p></li>
<li><p><code>&lt;containing_model&gt;_id</code>: the <code>id</code> of the model that declares the
+
<li><p><code>&lt;containing_model&gt;_id</code>:声明<code>ManyToManyField</code>的型号的<code>id</code></p></li>
<code>ManyToManyField</code>.</p></li>
+
<li><p><code>&lt;other_model&gt;_id</code><code>ManyToManyField</code>指向的型号的<code>id</code></p></li></ul>
<li><p><code>&lt;other_model&gt;_id</code>: the <code>id</code> of the model that the
 
<code>ManyToManyField</code> points to.</p></li></ul>
 
  
<p>如果``ManyToManyField``指向的来源和目标是相同的模型, 下面的字段会生成:</p>
+
<p>如果 <code>ManyToManyField</code> 指向和指向同一模型,则会生成以下字段:</p>
 
<ul>
 
<ul>
<li><p><code>id</code>: the primary key of the relation.</p></li>
+
<li><p><code>id</code>:关系的主键。</p></li>
<li><p><code>from_&lt;model&gt;_id</code>: the <code>id</code> of the instance which points at the
+
<li><p><code>from_&lt;model&gt;_id</code>:指向模型的实例的<code>id</code>(即 源实例)。</p></li>
model (i.e. the source instance).</p></li>
+
<li><p><code>to_&lt;model&gt;_id</code>:关系指向的实例的<code>id</code>(即 目标模型实例)。</p></li></ul>
<li><p><code>to_&lt;model&gt;_id</code>: the <code>id</code> of the instance to which the relationship
 
points (i.e. the target model instance).</p></li></ul>
 
  
<p>这个类可以用来查询联接给出模型实例的记录,使用方式和普通模型类似。</p></dd></dl>
+
<p>这个类可以像普通模型一样,用于查询给定模型实例的关联记录:</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>through_fields</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">through_fields</span></span></dt>
<dd><p>仅在明确给出一个自定义中间模型时使用。django将会正常地的决定使用中间模型的那些字段来自动地建立一个多对多的关系。然而,考虑下面的模型。</p>
+
<dd><p>仅在指定自定义中介模型时使用。 Django 通常会确定使用中间模型的哪些字段以自动建立多对多关系。 但是,请考虑以下模型:</p>
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db import models
+
<syntaxhighlight lang="python">from django.db import models
  
 
class Person(models.Model):
 
class Person(models.Model):
第1,911行: 第1,514行:
 
         Person,
 
         Person,
 
         on_delete=models.CASCADE,
 
         on_delete=models.CASCADE,
         related_name=&quot;membership_invites&quot;,
+
         related_name="membership_invites",
 
     )
 
     )
     invite_reason = models.CharField(max_length=64)</pre>
+
     invite_reason = models.CharField(max_length=64)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Membership 有*两个*外键``Person``(<code>person````inviter</code>),这使得联接关系显的歧义,django并不知道使用哪一个。这个例子中,你必须显式的指定Django应该使用哪个外键, 通过``through_fields``, 就想上例中一样。</p>
+
<p><code>Membership</code>''两个''外键到<code>Person</code>(<code>person</code><code>inviter</code>),这使得关系模糊,Django无法知道使用哪一个。 在这种情况下,您必须使用 <code>through_fields</code> 明确指定 Django 应该使用哪些外键,如上例所示。</p>
<p><code>through_fields``接受一个2元组(``fiels1</code><code>fields2</code>),其中``fields1``是多对多关系字段被定义的那个模型的外键名称(本例中的``group``), <code>fields2``是目标模型的外键名称(本例中的``person</code>)。</p>
+
<p><code>through_fields</code> 接受一个二元组 <code>('field1', 'field2')</code>,其中 <code>field1</code> 是模型的外键名称 [[#django.db.models.ManyToManyField|ManyToManyField]] 在 (<code>group</code> 在这种情况下),以及 <code>field2</code> 目标模型的外键名称(在这种情况下为 <code>person</code>)。</p>
<p>当你的中介表中有不止一个外键指向任一(或均)参与多对多关系的模型时, 你*必须*指定``through_fields``。这通用适用于``:ref:递归关系 &lt;recursive-relationships&gt; [[#id1|<span id="id2" class="problematic">``</span>]]中,场景是使用一个中介表并且不止两个外键指向同一个模型时,或者你需要显式地指定Django应该使用哪两个。</p>
+
<p>当您在一个中间模型上有多个外键指向参与多对多关系的任何(甚至两个)模型时,您 ''必须'' 指定 <code>through_fields</code>。 这也适用于 [[#recursive-relationships|递归关系]] 当使用中间模型并且模型有两个以上的外键时,或者您想明确指定应该使用哪两个 Django。</p>
<p>Recursive relationships using an intermediary model are always defined as
+
<p>使用中间模型的递归关系总是被定义为非对称的——也就是说,[[#django.db.models.ManyToManyField.symmetrical|对称=]]——因此,存在“源”和“目标”的概念。 在这种情况下,<code>'field1'</code> 将被视为关系的“源”,而 <code>'field2'</code> 将被视为“目标”。</p></dd></dl>
non-symmetrical -- that is, with [[#django.db.models.ManyToManyField.symmetrical|<code>symmetrical=False</code>]]
 
-- therefore, there is the concept of a &quot;source&quot; and a &quot;target&quot;. In that
 
case <code>'field1'</code> will be treated as the &quot;source&quot; of the relationship and
 
<code>'field2'</code> as the &quot;target&quot;.</p></dd></dl>
 
  
; <code>ManyToManyField.</code><code>db_table</code>
+
; <span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">db_table</span></span>
: The name of the table to create for storing the many-to-many data. If this is not provided, Django will assume a default name based upon the names of: the table for the model defining the relationship and the name of the field itself.
+
: 要创建的用于存储多对多数据的表的名称。 如果未提供,Django 将假定基于以下名称的默认名称:定义关系的模型表和字段本身的名称。
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>db_constraint</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">db_constraint</span></span></dt>
<dd><p>控制是否中介模型中外键的约束应该在数据库中被创建。默认值是True, 而且这几乎确定就是你需要的功能。将这个设为False会损坏数据的完整性。即便如此,一下场景一可能需要这样做:</p>
+
<dd><p>控制是否应在数据库中为中间表中的外键创建约束。 默认值为 <code>True</code>,这几乎肯定是您想要的; 将此设置为 <code>False</code> 可能对数据完整性非常不利。 也就是说,以下是您可能想要执行此操作的一些场景:</p>
 
<ul>
 
<ul>
 
<li><p>你有无效的冗余数据</p></li>
 
<li><p>你有无效的冗余数据</p></li>
<li><p>你正在共享你的数据库</p></li></ul>
+
<li><p>您正在对数据库进行分片。</p></li></ul>
  
<p>同时传递&quot;db_constraint&quot;和“through”会引发错误。</p></dd></dl>
+
<p>通过 <code>db_constraint</code> 和 <code>through</code> 都是错误的。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>ManyToManyField.</code><code>swappable</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ManyToManyField.</span></span><span class="sig-name descname"><span class="pre">swappable</span></span></dt>
<dd><p>Controls the migration framework's reaction if this [[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]]
+
<dd><p>如果此 [[#django.db.models.ManyToManyField|ManyToManyField]] 指向可交换模型,则控制迁移框架的反应。 如果它是 <code>True</code> - 默认值 - 那么如果 [[#django.db.models.ManyToManyField|ManyToManyField]] 指向的模型与 <code>settings.AUTH_USER_MODEL</code>(或其他可交换模型设置)的当前值匹配,则该关系将使用对设置的引用而不是直接对模型的引用存储在迁移中。</p>
is pointing at a swappable model. If it is <code>True</code> - the default -
+
<p>如果您确定您的模型应始终指向换入模型,您只想将其覆盖为 <code>False</code> - 例如,如果它是专为您的自定义用户模型设计的配置文件模型。</p>
then if the [[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]] is pointing at a model which matches
+
<p>如果有疑问,请将其保留为默认值 <code>True</code>。</p></dd></dl>
the current value of <code>settings.AUTH_USER_MODEL</code> (or another swappable
 
model setting) the relationship will be stored in the migration using
 
a reference to the setting, not to the model directly.</p>
 
<p>You only want to override this to be <code>False</code> if you are sure your
 
model should always point towards the swapped-in model - for example,
 
if it is a profile model designed specifically for your custom user model.</p>
 
<p>如果不确定,就保留它在默认为``True``的状态。</p></dd></dl>
 
  
[[#django.db.models.ManyToManyField|<code>ManyToManyField</code>]] does not support [[#django.db.models.Field.validators|<code>validators</code>]].
+
[[#django.db.models.ManyToManyField|ManyToManyField]] 不支持 [[#django.db.models.Field.validators|验证器]]
  
[[#django.db.models.Field.null|<code>null</code>]] has no effect since there is no way to require a
+
[[#django.db.models.Field.null|null]] 不起作用,因为无法在数据库级别要求关系。
relationship at the database level.
 
  
  
第1,963行: 第1,554行:
 
<div id="onetoonefield" class="section">
 
<div id="onetoonefield" class="section">
  
=== <code>OneToOneField</code> ===
+
=== OneToOneField ===
  
; ''class'' <code>OneToOneField</code><span class="sig-paren">(</span>''<span class="n">to</span>'', ''<span class="n">on_delete</span>'', ''<span class="n">parent_link</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="o">**</span><span class="n">options</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields/related.html#OneToOneField|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">OneToOneField</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">to</span></span>'', ''<span class="n"><span class="pre">on_delete</span></span>'', ''<span class="n"><span class="pre">parent_link</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">options</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A one-to-one relationship. Conceptually, this is similar to a
+
一对一的关系。 从概念上讲,这类似于具有 [[#django.db.models.Field.unique|unique=True]] [[#django.db.models.ForeignKey|ForeignKey]],但关系的“反向”侧将直接返回单个对象。
[[#django.db.models.ForeignKey|<code>ForeignKey</code>]] with [[#django.db.models.Field.unique|<code>unique=True</code>]], but the
 
&quot;reverse&quot; side of the relation will directly return a single object.
 
  
This is most useful as the primary key of a model which &quot;extends&quot;
+
这是作为模型的主键最有用的,它以某种方式“扩展”了另一个模型; [[../../../topics/db/models#multi-table-inheritance|多表继承]]例如通过添加从子模型到父模型的隐式一对一关系来实现。
another model in some way; [[../../../topics/db/models#multi-table-inheritance|<span class="std std-ref">多表继承</span>]] is
 
implemented by adding an implicit one-to-one relation from the child
 
model to the parent model, for example.
 
  
One positional argument is required: the class to which the model will be
+
需要一个位置参数:与模型相关的类。 这与 [[#django.db.models.ForeignKey|ForeignKey]] 的工作方式完全相同,包括所有关于 [[#recursive-relationships|recursive]] [[#lazy-relationships|lazy]] 关系的选项。
related. This works exactly the same as it does for [[#django.db.models.ForeignKey|<code>ForeignKey</code>]],
 
including all the options regarding [[#recursive-relationships|<span class="std std-ref">recursive</span>]]
 
and [[#lazy-relationships|<span class="std std-ref">lazy</span>]] relationships.
 
  
If you do not specify the [[#django.db.models.ForeignKey.related_name|<code>related_name</code>]] argument for the
+
如果您没有为 <code>OneToOneField</code> 指定 [[#django.db.models.ForeignKey.related_name|related_name]] 参数,Django 将使用当前模型的小写名称作为默认值。
<code>OneToOneField</code>, Django will use the lowercase name of the current model as
 
default value.
 
  
With the following example:
+
使用以下示例:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第1,992行: 第1,573行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.conf import settings
+
<syntaxhighlight lang="python">from django.conf import settings
 
from django.db import models
 
from django.db import models
  
第2,004行: 第1,585行:
 
         on_delete=models.CASCADE,
 
         on_delete=models.CASCADE,
 
         related_name='supervisor_of',
 
         related_name='supervisor_of',
     )</pre>
+
     )</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
your resulting <code>User</code> model will have the following attributes:
+
您生成的 <code>User</code> 模型将具有以下属性:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第2,015行: 第1,596行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; user = User.objects.get(pk=1)
+
<syntaxhighlight lang="python">>>> user = User.objects.get(pk=1)
&gt;&gt;&gt; hasattr(user, 'myspecialuser')
+
>>> hasattr(user, 'myspecialuser')
 
True
 
True
&gt;&gt;&gt; hasattr(user, 'supervisor_of')
+
>>> hasattr(user, 'supervisor_of')
True</pre>
+
True</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A <code>DoesNotExist</code> exception is raised when accessing the reverse relationship
+
如果相关表中的条目不存在,则在访问反向关系时会引发 <code>DoesNotExist</code> 异常。 例如,如果用户没有由 <code>MySpecialUser</code> 指定的主管:
if an entry in the related table doesn't exist. For example, if a user doesn't
 
have a supervisor designated by <code>MySpecialUser</code>:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第2,032行: 第1,611行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; user.supervisor_of
+
<syntaxhighlight lang="python">>>> user.supervisor_of
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
     ...
 
     ...
DoesNotExist: User matching query does not exist.</pre>
+
DoesNotExist: User matching query does not exist.</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Additionally, <code>OneToOneField</code> accepts all of the extra arguments
+
此外, <code>OneToOneField</code> 接受 [[#django.db.models.ForeignKey|ForeignKey]] 接受的所有额外参数,以及一个额外参数:
accepted by [[#django.db.models.ForeignKey|<code>ForeignKey</code>]], plus one extra argument:
 
  
; <code>OneToOneField.</code><code>parent_link</code>
+
; <span class="sig-prename descclassname"><span class="pre">OneToOneField.</span></span><span class="sig-name descname"><span class="pre">parent_link</span></span>
: When <code>True</code> and used in a model which inherits from another [[../../../glossary#term-concrete-model|<span class="xref std std-term">concrete model</span>]], indicates that this field should be used as the link back to the parent class, rather than the extra <code>OneToOneField</code> which would normally be implicitly created by subclassing.
+
: <code>True</code> 用于从另一个 [[../../../glossary#term-concrete-model|具体模型]] 继承的模型中时,表明该字段应用作返回父类的链接,而不是额外的 <code>OneToOneField</code> ] 通常由子类化隐式创建。
  
See [[../../../topics/db/examples/one_to_one|<span class="doc">One-to-one relationships</span>]] for usage
+
有关 <code>OneToOneField</code> 的使用示例,请参阅 [[../../../topics/db/examples/one_to_one|一对一关系]]
examples of <code>OneToOneField</code>.
 
  
  
第2,055行: 第1,632行:
 
<div id="field-api-reference" class="section">
 
<div id="field-api-reference" class="section">
  
== Field API reference ==
+
== 字段 API 参考 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>Field</code>[[../../_modules/django/db/models/fields.html#Field|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">Field</span></span></dt>
<dd><p><code>Field</code> is an abstract class that represents a database table column.
+
<dd><p><code>Field</code> 是代表数据库表列的抽象类。 Django 使用字段来创建数据库表 ([[#django.db.models.Field.db_type|db_type()]]),将 Python 类型映射到数据库 ([[#django.db.models.Field.get_prep_value|get_prep_value()]]),反之亦然 ([[#django.db.models.Field.from_db_value|from_db_value()]] ])。</p>
Django uses fields to create the database table ([[#django.db.models.Field.db_type|<code>db_type()</code>]]), to map
+
<p>因此,字段是不同 Django API 中的基本部分,尤其是 [[../instances#django.db.models|models]] [[../querysets#django.db.models.query|querysets]]</p>
Python types to database ([[#django.db.models.Field.get_prep_value|<code>get_prep_value()</code>]]) and vice-versa
+
<p>在模型中,字段被实例化为类属性并表示特定的表列,请参阅 [[../../../topics/db/models|Models]]。 它具有 [[#django.db.models.Field.null|null]] [[#django.db.models.Field.unique|unique]] 等属性,以及 Django 用于将字段值映射到数据库特定值的方法。</p>
([[#django.db.models.Field.from_db_value|<code>from_db_value()</code>]]).</p>
+
<p><code>Field</code> [[../lookups#django.db.models.lookups|RegisterLookupMixin]] 的子类,因此 [[../lookups#django.db.models|Transform]] [[../lookups#django.db.models|Lookup]] 都可以在其上注册以用于 <code>QuerySet</code> ]s(例如 <code>field_name__exact=&quot;foo&quot;</code>)。 默认情况下已注册所有 [[../querysets#field-lookups|内置查找]] </p>
<p>A field is thus a fundamental piece in different Django APIs, notably,
+
<p>Django 的所有内置字段,例如 [[#django.db.models.CharField|CharField]],都是 <code>Field</code> 的特定实现。 如果您需要自定义字段,您可以对任何内置字段进行子类化,也可以从头开始编写 <code>Field</code>。 无论哪种情况,请参阅 [[../../../howto/custom-model-fields|编写自定义模型字段]] </p>
[[../instances#django.db.models|<code>models</code>]] and [[../querysets#django.db.models.query|<code>querysets</code>]].</p>
 
<p>In models, a field is instantiated as a class attribute and represents a
 
particular table column, see [[../../../topics/db/models|<span class="doc">模型</span>]]. It has attributes
 
such as [[#django.db.models.Field.null|<code>null</code>]] and [[#django.db.models.Field.unique|<code>unique</code>]], and methods that Django uses to
 
map the field value to database-specific values.</p>
 
<p>A <code>Field</code> is a subclass of
 
[[../lookups#django.db.models.lookups|<code>RegisterLookupMixin</code>]] and thus both
 
[[../lookups#django.db.models|<code>Transform</code>]] and
 
[[../lookups#django.db.models|<code>Lookup</code>]] can be registered on it to be used
 
in <code>QuerySet</code>s (e.g. <code>field_name__exact=&quot;foo&quot;</code>). All [[../querysets#field-lookups|<span class="std std-ref">built-in
 
lookups</span>]] are registered by default.</p>
 
<p>All of Django's built-in fields, such as [[#django.db.models.CharField|<code>CharField</code>]], are particular
 
implementations of <code>Field</code>. If you need a custom field, you can either
 
subclass any of the built-in fields or write a <code>Field</code> from scratch. In
 
either case, see [[../../../howto/custom-model-fields|<span class="doc">编写自定义模型字段(model fields)</span>]].</p>
 
 
<dl>
 
<dl>
<dt><code>description</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">description</span></span></dt>
<dd><p>A verbose description of the field, e.g. for the
+
<dd><p>字段的详细描述,例如 对于 [[../../contrib/admin/admindocs#module-django.contrib|django.contrib.admindocs]] 应用程序。</p>
[[../../contrib/admin/admindocs#module-django.contrib|<code>django.contrib.admindocs</code>]] application.</p>
+
<p>描述可以是以下形式:</p>
<p>The description can be of the form:</p>
 
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>description = _(&quot;String (up to %(max_length)s)&quot;)</pre>
+
<syntaxhighlight lang="python">description = _("String (up to %(max_length)s)")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>where the arguments are interpolated from the field's <code>__dict__</code>.</p></dd></dl>
+
<p>其中参数是从字段的 <code>__dict__</code> 插入的。</p></dd></dl>
  
<p>To map a <code>Field</code> to a database-specific type, Django exposes several
+
<p>要将 <code>Field</code> 映射到特定于数据库的类型,Django 公开了几种方法:</p>
methods:</p>
 
 
<dl>
 
<dl>
<dt><code>get_internal_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.get_internal_type|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">get_internal_type</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a string naming this field for backend specific purposes.
+
<dd><p>返回命名此字段的字符串以用于后端特定目的。 默认情况下,它返回类名。</p>
By default, it returns the class name.</p>
+
<p>有关自定义字段的用法,请参阅 [[../../../howto/custom-model-fields#emulating-built-in-field-types|模拟内置字段类型]] </p></dd></dl>
<p>See [[../../../howto/custom-model-fields#emulating-built-in-field-types|<span class="std std-ref">仿造内置字段类型</span>]] for usage in custom fields.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>db_type</code><span class="sig-paren">(</span>''<span class="n">connection</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.db_type|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">db_type</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">connection</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the database column data type for the [[#django.db.models.Field|<code>Field</code>]], taking
+
<dd><p>返回 [[#django.db.models.Field|字段]] 的数据库列数据类型,同时考虑 <code>connection</code></p>
into account the <code>connection</code>.</p>
+
<p>有关自定义字段中的用法,请参阅 [[../../../howto/custom-model-fields#custom-database-types|自定义数据库类型]] </p></dd></dl>
<p>See [[../../../howto/custom-model-fields#custom-database-types|<span class="std std-ref">自定义数据库类型</span>]] for usage in custom fields.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>rel_db_type</code><span class="sig-paren">(</span>''<span class="n">connection</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.rel_db_type|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">rel_db_type</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">connection</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the database column data type for fields such as <code>ForeignKey</code>
+
<dd><p>返回指向 [[#django.db.models.Field|字段]] 的 <code>ForeignKey</code> 和 <code>OneToOneField</code> 等字段的数据库列数据类型,同时考虑 <code>connection</code></p>
and <code>OneToOneField</code> that point to the [[#django.db.models.Field|<code>Field</code>]], taking
+
<p>有关自定义字段中的用法,请参阅 [[../../../howto/custom-model-fields#custom-database-types|自定义数据库类型]] </p></dd></dl>
into account the <code>connection</code>.</p>
 
<p>See [[../../../howto/custom-model-fields#custom-database-types|<span class="std std-ref">自定义数据库类型</span>]] for usage in custom fields.</p></dd></dl>
 
  
<p>There are three main situations where Django needs to interact with the
+
<p>Django 主要有三种情况需要与数据库后台和字段进行交互。</p>
database backend and fields:</p>
 
 
<ul>
 
<ul>
<li><p>when it queries the database (Python value -&gt; database backend value)</p></li>
+
<li><p>当它查询数据库时(Python 值 -&gt; 数据库后台值)</p></li>
<li><p>when it loads data from the database (database backend value -&gt; Python
+
<li><p>当它从数据库中加载数据时(数据库后台值 -&gt; Python 值)</p></li>
value)</p></li>
+
<li><p>当它保存到数据库时(Python 值 -&gt; 数据库后端值)</p></li></ul>
<li><p>when it saves to the database (Python value -&gt; database backend value)</p></li></ul>
 
  
<p>When querying, [[#django.db.models.Field.get_db_prep_value|<code>get_db_prep_value()</code>]] and [[#django.db.models.Field.get_prep_value|<code>get_prep_value()</code>]] are used:</p>
+
<p>查询时使用[[#django.db.models.Field.get_db_prep_value|get_db_prep_value()]][[#django.db.models.Field.get_prep_value|get_prep_value()]]</p>
 
<dl>
 
<dl>
<dt><code>get_prep_value</code><span class="sig-paren">(</span>''<span class="n">value</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.get_prep_value|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">get_prep_value</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>''<span class="sig-paren">)</span></dt>
<dd><p><code>value</code> is the current value of the model's attribute, and the method
+
<dd><p><code>value</code> 是模型属性的当前值,该方法应以已准备好用作查询中的参数的格式返回数据。</p>
should return data in a format that has been prepared for use as a
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#converting-python-objects-to-query-values|将 Python 对象转换为查询值]] </p></dd></dl>
parameter in a query.</p>
 
<p>See [[../../../howto/custom-model-fields#converting-python-objects-to-query-values|<span class="std std-ref">将 Python 转为查询值</span>]] for usage.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>get_db_prep_value</code><span class="sig-paren">(</span>''<span class="n">value</span>'', ''<span class="n">connection</span>'', ''<span class="n">prepared</span><span class="o">=</span><span class="default_value">False</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.get_db_prep_value|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">get_db_prep_value</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>'', ''<span class="n"><span class="pre">connection</span></span>'', ''<span class="n"><span class="pre">prepared</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Converts <code>value</code> to a backend-specific value. By default it returns
+
<dd><p><code>value</code> 转换为后端特定的值。 默认情况下,如果 <code>prepared=True</code> [[#django.db.models.Field.get_prep_value|get_prep_value()]] 如果是 <code>False</code>,它会返回 <code>value</code></p>
<code>value</code> if <code>prepared=True</code> and [[#django.db.models.Field.get_prep_value|<code>get_prep_value()</code>]] if is
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#converting-query-values-to-database-values|将查询值转换为数据库值]] </p></dd></dl>
<code>False</code>.</p>
 
<p>See [[../../../howto/custom-model-fields#converting-query-values-to-database-values|<span class="std std-ref">将查询值转为数据库值</span>]] for usage.</p></dd></dl>
 
  
<p>When loading data, [[#django.db.models.Field.from_db_value|<code>from_db_value()</code>]] is used:</p>
+
<p>加载数据时,使用[[#django.db.models.Field.from_db_value|from_db_value()]]</p>
 
<dl>
 
<dl>
<dt><code>from_db_value</code><span class="sig-paren">(</span>''<span class="n">value</span>'', ''<span class="n">expression</span>'', ''<span class="n">connection</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">from_db_value</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>'', ''<span class="n"><span class="pre">expression</span></span>'', ''<span class="n"><span class="pre">connection</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Converts a value as returned by the database to a Python object. It is
+
<dd><p>将数据库返回的值转换为 Python 对象。 与 [[#django.db.models.Field.get_prep_value|get_prep_value()]] 相反。</p>
the reverse of [[#django.db.models.Field.get_prep_value|<code>get_prep_value()</code>]].</p>
+
<p>这个方法不用于大多数内置字段,因为数据库后端已经返回了正确的 Python 类型,或者后端自己进行了转换。</p>
<p>This method is not used for most built-in fields as the database
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#converting-values-to-python-objects|将值转换为 Python 对象]] </p>
backend already returns the correct Python type, or the backend itself
 
does the conversion.</p>
 
<p>See [[../../../howto/custom-model-fields#converting-values-to-python-objects|<span class="std std-ref">将值转为 Python 对象</span>]] for usage.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>For performance reasons, <code>from_db_value</code> is not implemented as a
+
<p>出于性能原因,<code>from_db_value</code> 没有在不需要它的字段(所有 Django 字段)上实现为无操作。 因此,您不能在定义中调用 <code>super</code></p>
no-op on fields which do not require it (all Django fields).
 
Consequently you may not call <code>super</code> in your definition.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
<p>When saving, [[#django.db.models.Field.pre_save|<code>pre_save()</code>]] and [[#django.db.models.Field.get_db_prep_save|<code>get_db_prep_save()</code>]] are used:</p>
+
<p>保存时使用[[#django.db.models.Field.pre_save|pre_save()]][[#django.db.models.Field.get_db_prep_save|get_db_prep_save()]]</p>
 
<dl>
 
<dl>
<dt><code>get_db_prep_save</code><span class="sig-paren">(</span>''<span class="n">value</span>'', ''<span class="n">connection</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.get_db_prep_save|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">get_db_prep_save</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>'', ''<span class="n"><span class="pre">connection</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Same as the [[#django.db.models.Field.get_db_prep_value|<code>get_db_prep_value()</code>]], but called when the field value
+
<dd><p>[[#django.db.models.Field.get_db_prep_value|get_db_prep_value()]] 相同,但在字段值必须 ''saved'' 到数据库时调用。 默认返回 [[#django.db.models.Field.get_db_prep_value|get_db_prep_value()]]</p></dd></dl>
must be ''saved'' to the database. By default returns
 
[[#django.db.models.Field.get_db_prep_value|<code>get_db_prep_value()</code>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>pre_save</code><span class="sig-paren">(</span>''<span class="n">model_instance</span>'', ''<span class="n">add</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.pre_save|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">pre_save</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">model_instance</span></span>'', ''<span class="n"><span class="pre">add</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Method called prior to [[#django.db.models.Field.get_db_prep_save|<code>get_db_prep_save()</code>]] to prepare the value
+
<dd><p>[[#django.db.models.Field.get_db_prep_save|get_db_prep_save()]] 之前调用的方法在保存之前准备值(例如 对于 [[#django.db.models.DateField.auto_now|DateField.auto_now]])。</p>
before being saved (e.g. for [[#django.db.models.DateField.auto_now|<code>DateField.auto_now</code>]]).</p>
+
<p><code>model_instance</code>为该字段所属的实例,<code>add</code>为该实例是否第一次存入数据库。</p>
<p><code>model_instance</code> is the instance this field belongs to and <code>add</code>
+
<p>它应该从 <code>model_instance</code> 为该字段返回适当属性的值。 属性名称在 <code>self.attname</code> 中(这是由 [[#django.db.models.Field|Field]] 设置的)。</p>
is whether the instance is being saved to the database for the first
+
<p>请参阅 [[../../../howto/custom-model-fields#preprocessing-values-before-saving|保存前的预处理值]] 以了解用法。</p></dd></dl>
time.</p>
 
<p>It should return the value of the appropriate attribute from
 
<code>model_instance</code> for this field. The attribute name is in
 
<code>self.attname</code> (this is set up by [[#django.db.models.Field|<code>Field</code>]]).</p>
 
<p>See [[../../../howto/custom-model-fields#preprocessing-values-before-saving|<span class="std std-ref">在保存前预处理数值</span>]] for usage.</p></dd></dl>
 
  
<p>Fields often receive their values as a different type, either from
+
<p>字段经常以不同的类型接收它们的值,要么来自序列化,要么来自表单。</p>
serialization or from forms.</p>
 
 
<dl>
 
<dl>
<dt><code>to_python</code><span class="sig-paren">(</span>''<span class="n">value</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.to_python|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">to_python</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">value</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Converts the value into the correct Python object. It acts as the
+
<dd><p>将值转换为正确的 Python 对象。 它的作用与 [[#django.db.models.Field.value_to_string|value_to_string()]] 的相反,也在 [[../instances#django.db.models.Model|clean()]] 中调用。</p>
reverse of [[#django.db.models.Field.value_to_string|<code>value_to_string()</code>]], and is also called in
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#converting-values-to-python-objects|将值转换为 Python 对象]] </p></dd></dl>
[[../instances#django.db.models.Model|<code>clean()</code>]].</p>
 
<p>See [[../../../howto/custom-model-fields#converting-values-to-python-objects|<span class="std std-ref">将值转为 Python 对象</span>]] for usage.</p></dd></dl>
 
  
<p>Besides saving to the database, the field also needs to know how to
+
<p>除了保存到数据库,字段还需要知道如何将其值序列化。</p>
serialize its value:</p>
 
 
<dl>
 
<dl>
<dt><code>value_from_object</code><span class="sig-paren">(</span>''<span class="n">obj</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.value_from_object|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">value_from_object</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">obj</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the field's value for the given model instance.</p>
+
<dd><p>返回给定模型实例的字段值。</p>
<p>This method is often used by [[#django.db.models.Field.value_to_string|<code>value_to_string()</code>]].</p></dd></dl>
+
<p>这个方法经常被 [[#django.db.models.Field.value_to_string|value_to_string()]] 使用。</p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>value_to_string</code><span class="sig-paren">(</span>''<span class="n">obj</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.value_to_string|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">value_to_string</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">obj</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Converts <code>obj</code> to a string. Used to serialize the value of the field.</p>
+
<dd><p><code>obj</code> 转换为字符串。 用于序列化字段的值。</p>
<p>See [[../../../howto/custom-model-fields#converting-model-field-to-serialization|<span class="std std-ref">为序列化转换字段数据</span>]] for usage.</p></dd></dl>
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#converting-model-field-to-serialization|转换字段数据以进行序列化]] </p></dd></dl>
  
<p>When using [[../../../topics/forms/modelforms#django.forms|<code>model forms</code>]], the <code>Field</code>
+
<p>当使用[[../../../topics/forms/modelforms#django.forms|模型表单]]时,<code>Field</code>需要知道它应该用哪个表单字段表示:</p>
needs to know which form field it should be represented by:</p>
 
 
<dl>
 
<dl>
<dt><code>formfield</code><span class="sig-paren">(</span>''<span class="n">form_class</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">choices_form_class</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">**</span><span class="n">kwargs</span>''<span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.formfield|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">formfield</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">form_class</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">choices_form_class</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Returns the default [[../../forms/fields#django.forms|<code>django.forms.Field</code>]] of this field for
+
<dd><p>[[../../../topics/forms/modelforms#django.forms|ModelForm]] 返回此字段的默认 [[../../forms/fields#django.forms|django.forms.Field]]</p>
[[../../../topics/forms/modelforms#django.forms|<code>ModelForm</code>]].</p>
+
<p>默认情况下,如果 <code>form_class</code> <code>choices_form_class</code> 都是 <code>None</code>,则使用 [[../../forms/fields#django.forms|CharField]]。 如果该字段具有 [[#django.db.models.Field.choices|choices]] 且未指定 <code>choices_form_class</code>,则使用 [[../../forms/fields#django.forms|TypedChoiceField]]</p>
<p>By default, if both <code>form_class</code> and <code>choices_form_class</code> are
+
<p>有关用法,请参阅 [[../../../howto/custom-model-fields#specifying-form-field-for-model-field|指定模型字段的表单字段]] </p></dd></dl>
<code>None</code>, it uses [[../../forms/fields#django.forms|<code>CharField</code>]]. If the field has
 
[[#django.db.models.Field.choices|<code>choices</code>]] and <code>choices_form_class</code>
 
isn't specified, it uses [[../../forms/fields#django.forms|<code>TypedChoiceField</code>]].</p>
 
<p>See [[../../../howto/custom-model-fields#specifying-form-field-for-model-field|<span class="std std-ref">为模型字段指定表单字段</span>]] for usage.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>deconstruct</code><span class="sig-paren">(</span><span class="sig-paren">)</span>[[../../_modules/django/db/models/fields.html#Field.deconstruct|<span class="viewcode-link">[源代码]</span>]]</dt>
+
<dt><span class="sig-name descname"><span class="pre">deconstruct</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a 4-tuple with enough information to recreate the field:</p>
+
<dd><p>返回一个包含足够信息的四元元组来重新创建字段。</p>
 
<ol>
 
<ol>
<li><p>The name of the field on the model.</p></li>
+
<li><p>模型上的字段名称。</p></li>
<li><p>The import path of the field (e.g. <code>&quot;django.db.models.IntegerField&quot;</code>).
+
<li><p>字段的导入路径(例如 <code>&quot;django.db.models.IntegerField&quot;</code>)。 这应该是最便携的版本,所以不那么具体可能会更好。</p></li>
This should be the most portable version, so less specific may be better.</p></li>
+
<li><p>一个位置参数的列表。</p></li>
<li><p>A list of positional arguments.</p></li>
+
<li><p>一个关键字参数的字典。</p></li></ol>
<li><p>A dict of keyword arguments.</p></li></ol>
 
  
<p>This method must be added to fields prior to 1.7 to migrate its data
+
<p>必须将此方法添加到 1.7 之前的字段中才能使用 [[../../../topics/migrations|Migrations]] 迁移其数据。</p></dd></dl>
using [[../../../topics/migrations|<span class="doc">迁移</span>]].</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
第2,230行: 第1,757行:
  
 
<span id="model-field-attributes"></span>
 
<span id="model-field-attributes"></span>
= Field attribute reference =
+
= 字段属性参考 =
  
Every <code>Field</code> instance contains several attributes that allow
+
每个 <code>Field</code> 实例都包含几个允许自省其行为的属性。 当您需要编写依赖于字段功能的代码时,请使用这些属性而不是 <code>isinstance</code> 检查。 这些属性可以与 [[../meta#model-meta-field-api|Model._meta API]] 一起使用,以缩小特定字段类型的搜索范围。 自定义模型字段应实现这些标志。
introspecting its behavior. Use these attributes instead of <code>isinstance</code>
 
checks when you need to write code that depends on a field's functionality.
 
These attributes can be used together with the [[../meta#model-meta-field-api|<span class="std std-ref">Model._meta API</span>]] to narrow down a search for specific field types.
 
Custom model fields should implement these flags.
 
  
 
<div id="attributes-for-fields" class="section">
 
<div id="attributes-for-fields" class="section">
  
== Attributes for fields ==
+
== 字段的属性 ==
  
; <code>Field.</code><code>auto_created</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">auto_created</span></span>
: Boolean flag that indicates if the field was automatically created, such as the <code>OneToOneField</code> used by model inheritance.
+
: 指示字段是否自动创建的布尔标志,例如模型继承使用的 <code>OneToOneField</code>
  
; <code>Field.</code><code>concrete</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">concrete</span></span>
: Boolean flag that indicates if the field has a database column associated with it.
+
: 布尔值标志,表示该字段是否有与之相关的数据库列。
  
 
<dl>
 
<dl>
<dt><code>Field.</code><code>hidden</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">hidden</span></span></dt>
<dd><p>Boolean flag that indicates if a field is used to back another non-hidden
+
<dd><p>布尔标志,指示一个字段是否用于支持另一个非隐藏字段的功能(例如 <code>content_type</code> <code>object_id</code> 字段组成 <code>GenericForeignKey</code>)。 <code>hidden</code> 标志用于区分模型上字段的公共子集与模型上的所有字段。</p>
field's functionality (e.g. the <code>content_type</code> and <code>object_id</code> fields
 
that make up a <code>GenericForeignKey</code>). The <code>hidden</code> flag is used to
 
distinguish what constitutes the public subset of fields on the model from
 
all the fields on the model.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>[[../meta#django.db.models.options.Options|<code>Options.get_fields()</code>]]
+
<p>[[../meta#django.db.models.options.Options|Options.get_fields()]] 默认排除隐藏字段。 传入 <code>include_hidden=True</code> 返回结果中的隐藏字段。</p>
excludes hidden fields by default. Pass in <code>include_hidden=True</code> to
 
return hidden fields in the results.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>Field.</code><code>is_relation</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">is_relation</span></span>
: Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g. <code>ForeignKey</code>, <code>ManyToManyField</code>, <code>OneToOneField</code>, etc.).
+
: 指示字段是否包含对其功能的一个或多个其他模型的引用的布尔标志(例如 <code>ForeignKey</code><code>ManyToManyField</code><code>OneToOneField</code> 等)。
  
; <code>Field.</code><code>model</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">model</span></span>
: Returns the model on which the field is defined. If a field is defined on a superclass of a model, <code>model</code> will refer to the superclass, not the class of the instance.
+
: 返回定义字段的模型。 如果在模型的超类上定义了字段,则 <code>model</code> 将引用超类,而不是实例的类。
  
  
第2,274行: 第1,791行:
 
<div id="attributes-for-fields-with-relations" class="section">
 
<div id="attributes-for-fields-with-relations" class="section">
  
== Attributes for fields with relations ==
+
== 有关系的字段的属性 ==
  
These attributes are used to query for the cardinality and other details of a
+
这些属性用于查询关系的基数和其他详细信息。 这些属性存在于所有字段中; 但是,如果字段是关系类型 ([[#django.db.models.Field.is_relation|Field.is_relation=True]]),它们将只有布尔值(而不是 <code>None</code>)。
relation. These attribute are present on all fields; however, they will only
 
have boolean values (rather than <code>None</code>) if the field is a relation type
 
([[#django.db.models.Field.is_relation|<code>Field.is_relation=True</code>]]).
 
  
; <code>Field.</code><code>many_to_many</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">many_to_many</span></span>
: Boolean flag that is <code>True</code> if the field has a many-to-many relation; <code>False</code> otherwise. The only field included with Django where this is <code>True</code> is <code>ManyToManyField</code>.
+
: 如果字段具有多对多关系,则布尔标志为 <code>True</code><code>False</code> 否则。 Django 中唯一包含 <code>True</code> 的字段是 <code>ManyToManyField</code>
  
; <code>Field.</code><code>many_to_one</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">many_to_one</span></span>
: Boolean flag that is <code>True</code> if the field has a many-to-one relation, such as a <code>ForeignKey</code>; <code>False</code> otherwise.
+
: 如果字段具有多对一关系,则为 <code>True</code> 的布尔标志,例如 <code>ForeignKey</code><code>False</code> 否则。
  
; <code>Field.</code><code>one_to_many</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">one_to_many</span></span>
: Boolean flag that is <code>True</code> if the field has a one-to-many relation, such as a <code>GenericRelation</code> or the reverse of a <code>ForeignKey</code>; <code>False</code> otherwise.
+
: 如果字段具有一对多关系,则布尔标志为 <code>True</code>,例如 <code>GenericRelation</code> <code>ForeignKey</code> 的反向; <code>False</code> 否则。
  
; <code>Field.</code><code>one_to_one</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">one_to_one</span></span>
: Boolean flag that is <code>True</code> if the field has a one-to-one relation, such as a <code>OneToOneField</code>; <code>False</code> otherwise.
+
: 如果字段具有一对一关系,则为 <code>True</code> 的布尔标志,例如 <code>OneToOneField</code><code>False</code> 否则。
  
; <code>Field.</code><code>related_model</code>
+
; <span class="sig-prename descclassname"><span class="pre">Field.</span></span><span class="sig-name descname"><span class="pre">related_model</span></span>
: Points to the model the field relates to. For example, <code>Author</code> in <code>ForeignKey(Author, on_delete=models.CASCADE)</code>. The <code>related_model</code> for a <code>GenericForeignKey</code> is always <code>None</code>.
+
: 指向与该字段相关的模型。 例如,<code>ForeignKey(Author, on_delete=models.CASCADE)</code> 中的 <code>Author</code><code>GenericForeignKey</code> 的 <code>related_model</code> 始终为 <code>None</code>
  
  
第2,300行: 第1,814行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Django 2.2.x 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Django 2.2.x 文档]]

2021年10月31日 (日) 04:05的最新版本

模型字段参考

本文档包含 Field 的所有 API 参考,包括 Django 提供的 field optionsfield types

也可以看看

如果内置字段不起作用,您可以尝试 django-localflavordocumentation),其中包含对特定国家和文化有用的各种代码。

此外,您可以轻松地 编写自己的自定义模型字段


笔记

从技术上讲,这些模型在 django.db.models.fields 中定义,但为了方便起见,它们被导入到 django.db.models 中; 标准约定是使用 from django.db import models 并将字段称为 models.<Foo>Field


字段选项

以下参数可用于所有字段类型。 都是可选的。

null

Field.null

如果是 True,Django 将在数据库中将空值存储为 NULL。 默认值为 False

避免在基于字符串的字段上使用 null,例如 CharFieldTextField。 如果基于字符串的字段具有 null=True,则意味着“无数据”有两个可能的值:NULL 和空字符串。 在大多数情况下,“无数据”有两个可能的值是多余的; Django 约定是使用空字符串,而不是 NULL。 一个例外是 CharField 同时设置了 unique=Trueblank=True。 在这种情况下,需要 null=True 以避免在保存具有空白值的多个对象时违反唯一约束。

对于基于字符串和非基于字符串的字段,如果您希望在表单中允许空值,您还需要设置 blank=True,因为 null 参数仅影响数据库存储(见 空白 )。

笔记

当使用 Oracle 数据库后端时,值 NULL 将被存储以表示空字符串,而不管该属性如何。


blank

Field.blank

如果是True,则该字段可以为空。 默认值为 False

请注意,这与 null 不同。 null 纯粹与数据库相关,而 blank 与验证相关。 如果字段具有 blank=True,则表单验证将允许输入空值。 如果字段具有 blank=False,则该字段将是必需的。


choices

Field.choices

一个 序列 由恰好两个项目的迭代组成(例如 [(A, B), (A, B) ...]) 用作此字段的选项。 如果给出了选择,则它们由 模型验证 强制执行,并且默认表单小部件将是带有这些选择的选择框,而不是标准文本字段。

每个元组中的第一个元素是要在模型上设置的实际值,第二个元素是人类可读的名称。 例如:

YEAR_IN_SCHOOL_CHOICES = [
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
]

通常,最好在模型类中定义选择,并为每个值定义一个适当命名的常量:

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

尽管您可以在模型类之外定义一个选项列表然后引用它,但是在模型类中定义每个选项的选项和名称会保留使用它的类的所有信息,并使选项易于引用(例如,Student.SOPHOMORE 将在导入 Student 模型的任何地方工作)。

您还可以将可用选项收集到可用于组织目的的命名组中:

MEDIA_CHOICES = [
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
]

每个元组中的第一个元素是应用于组的名称。 第二个元素是一个 2 元组的可迭代对象,每个 2 元组包含一个值和一个人类可读的选项名称。 分组选项可以与单个列表中的未分组选项组合(例如本例中的 unknown 选项)。

对于每个设置了 choices 的模型字段,Django 将添加一个方法来检索字段当前值的可读名称。 请参阅数据库 API 文档中的 get_FOO_display()

请注意,选择可以是任何序列对象——不一定是列表或元组。 这使您可以动态构建选择。 但是,如果您发现自己将 choices 修改为动态,则最好使用带有 ForeignKey 的适当数据库表。 choices 用于不会发生太大变化的静态数据,如果有的话。

笔记

每次 choices 的顺序更改时,都会创建一个新的迁移。


除非 blank=Falsedefault 一起在字段上设置,那么包含 "---------" 的标签将与选择框一起呈现。 要覆盖此行为,请向包含 Nonechoices 添加一个元组; 例如 (None, 'Your String For Display')。 或者,您可以使用空字符串而不是 None ,这是有意义的 - 例如在 CharField 上。


db_column

Field.db_column

用于此字段的数据库列的名称。 如果没有给出,Django 将使用该字段的名称。

如果您的数据库列名称是 SQL 保留字,或者包含 Python 变量名称中不允许的字符(尤其是连字符),那也没关系。 Django 在幕后引用列名和表名。


db_index

Field.db_index

如果是 True,将为此字段创建数据库索引。


db_tablespace

Field.db_tablespace

用于该字段索引的 数据库表空间 的名称(如果该字段已编入索引)。 默认是项目的 :setting:`DEFAULT_INDEX_TABLESPACE` 设置(如果已设置)或模型的 db_tablespace(如果有)。 如果后端不支持索引表空间,则忽略此选项。


default

Field.default

字段的默认值。 这可以是值或可调用对象。 如果可调用,则每次创建新对象时都会调用它。

默认值不能是可变对象(模型实例、listset 等),因为对该对象的同一实例的引用将用作所有对象的默认值新模型实例。 相反,将所需的默认值包装在一个可调用对象中。 例如,如果要为 JSONField 指定默认的 dict,请使用函数:

def contact_default():
    return {"email": "to1@example.com"}

contact_info = JSONField("ContactInfo", default=contact_default)

lambdas 不能用于像 default 这样的字段选项,因为它们不能被迁移 序列化 。 有关其他注意事项,请参阅该文档。

对于像 ForeignKey 这样映射到模型实例的字段,默认值应该是它们引用的字段的值(pk,除非设置了 to_field)而不是模型实例。

在创建新模型实例并且未为该字段提供值时使用默认值。 当字段为主键时,字段设置为None时也使用默认值。


editable

Field.editable

如果是 False,该字段将不会显示在 admin 或任何其他 ModelForm 中。 在 模型验证 期间也会跳过它们。 默认值为 True


error_messages

Field.error_messages

error_messages 参数允许您覆盖该字段将引发的默认消息。 传入一个字典,其键与要覆盖的错误消息匹配。

错误信息键包括 nullblankinvalidinvalid_choiceuniqueunique_for_date。 在下面的 字段类型 部分中为每个字段指定了其他错误消息键。

这些错误消息通常不会传播到表单。 请参阅 关于模型的 error_messages 的注意事项。


help_text

Field.help_text

与表单小部件一起显示的额外“帮助”文本。 即使您的字段未在表单上使用,它也可用于文档。

请注意,此值在自动生成的表单中是 而非 HTML 转义。 如果您愿意,这允许您在 help_text 中包含 HTML。 例如:

help_text="Please use the following format: <em>YYYY-MM-DD</em>."

或者,您可以使用纯文本和 django.utils.html.escape() 来转义任何 HTML 特殊字符。 确保您对可能来自不受信任用户的任何帮助文本进行转义以避免跨站点脚本攻击。


primary_key

Field.primary_key

如果是 True,则该字段是模型的主键。

如果你的模型中没有为任何字段指定 primary_key=True,Django 会自动添加一个 AutoField 来保存主键,所以你不需要设置 primary_key=True ] 在您的任何字段上,除非您想覆盖默认的主键行为。 有关更多信息,请参阅 自动主键字段

primary_key=True 意味着 null=Falseunique=True。 一个对象上只允许有一个主键。

主键字段是只读的。 如果您在现有对象上更改主键的值然后保存它,则会在旧对象旁边创建一个新对象。


unique

Field.unique

如果是 True,则该字段在整个表中必须是唯一的。

这是在数据库级别和模型验证中强制执行的。 如果您尝试在 unique 字段中保存具有重复值的模型,模型的 save() 方法将引发 django.db.IntegrityError .

此选项对除 ManyToManyFieldOneToOneField 之外的所有字段类型都有效。

注意,当 uniqueTrue 时,不需要指定 db_index,因为 unique 意味着创建索引。


unique_for_date

Field.unique_for_date

将此设置为 DateFieldDateTimeField 的名称,以要求此字段对于日期字段的值是唯一的。

例如,如果您有一个字段 title 具有 unique_for_date="pub_date",那么 Django 将不允许输入具有相同 titlepub_date 的两条记录.

请注意,如果您将其设置为指向 DateTimeField,则只会考虑该字段的日期部分。 此外,当 :setting:`USE_TZ`True 时,将在对象保存时的 当前时区 中进行检查。

这是在模型验证期间由 Model.validate_unique() 强制执行的,但不是在数据库级别执行的。 如果任何 unique_for_date 约束涉及不属于 ModelForm 的字段(例如,如果其中一个字段在 exclude 中列出或具有 editable= False), Model.validate_unique() 将跳过对该特定约束的验证。


unique_for_month

Field.unique_for_month

unique_for_date 类似,但要求该字段相对于月份而言是唯一的。


unique_for_year

Field.unique_for_year

unique_for_dateunique_for_month


verbose_name

Field.verbose_name

字段的可读名称。 如果没有给出详细名称,Django 将使用字段的属性名称自动创建它,将下划线转换为空格。 请参阅 详细字段名称


validators

Field.validators

要为此字段运行的验证器列表。 有关更多信息,请参阅 验证器文档

注册和获取查询

Field 实现了 查找注册 API。 API 可用于自定义字段类可用的查找,以及如何从字段中获取查找。


字段类型

AutoField

class AutoField(**options)

IntegerField 根据可用 ID 自动递增。 您通常不需要直接使用它; 如果您没有另外指定,主键字段将自动添加到您的模型中。 请参阅 自动主键字段


BigAutoField

class BigAutoField(**options)

一个 64 位整数,很像 AutoField,除了它保证适合从 19223372036854775807 的数字。


BigIntegerField

class BigIntegerField(**options)

一个 64 位整数,很像 IntegerField,除了它保证适合从 -92233720368547758089223372036854775807 的数字。 此字段的默认表单小部件是 TextInput


BinaryField

class BinaryField(max_length=None, **options)

存储原始二进制数据的字段。 可以分配 bytesbytearraymemoryview

默认情况下,BinaryFieldeditable 设置为 False,在这种情况下,它不能包含在 ModelForm 中。

2.1 版本变更: 旧版本不允许将 editable 设置为 True


BinaryField 有一个额外的可选参数:

BinaryField.max_length
字段的最大长度(以字符为单位)。 最大长度在 Django 的验证中使用 MaxLengthValidator 强制执行。

滥用 BinaryField

尽管您可能会考虑将文件存储在数据库中,但请考虑在 99% of 的情况下这是糟糕的设计。 该字段是 不是 替代正确的 静态文件 处理。


BooleanField

class BooleanField(**options)

一个 true/false 字段。

此字段的默认表单小部件是 CheckboxInput,或 NullBooleanSelect 如果 null=True

Field.default 未定义时,BooleanField 的默认值为 None

2.1 版本变更: 在旧版本中,此字段不允许 null=True,因此您必须使用 NullBooleanField 代替。 现在不鼓励使用后者,因为它可能会在未来版本的 Django 中被弃用。

在旧版本中,此字段隐式具有 blank=True。 您可以通过设置 blank=True 来恢复之前的行为。


CharField

class CharField(max_length=None, **options)

一个字符串字段,适用于小到大的字符串。

对于大量文本,请使用 TextField

此字段的默认表单小部件是 TextInput

CharField 有一个额外的必需参数:

CharField.max_length
字段的最大长度(以字符为单位)。 max_length 在数据库级别和 Django 的验证中使用 MaxLengthValidator 强制执行。

笔记

如果您正在编写一个必须可移植到多个数据库后端的应用程序,您应该注意某些后端对 max_length 的限制。 详情请参考数据库后端笔记


DateField

class DateField(auto_now=False, auto_now_add=False, **options)

一个日期,在 Python 中由 datetime.date 实例表示。 有一些额外的可选参数:

DateField.auto_now

每次保存对象时自动将字段设置为现在。 对“上次修改”时间戳很有用。 注意当前日期是 always used; 它不仅仅是您可以覆盖的默认值。

该字段仅在调用 Model.save() 时自动更新。 以其他方式(例如 QuerySet.update())更新其他字段时,该字段不会更新,但您可以在这样的更新中为该字段指定自定义值。

DateField.auto_now_add
首次创建对象时自动将字段设置为现在。 用于创建时间戳。 注意当前日期是 always used; 它不仅仅是您可以覆盖的默认值。 所以即使你在创建对象时为这个字段设置了一个值,它也会被忽略。 如果您希望能够修改此字段,请设置以下内容而不是 auto_now_add=True

此字段的默认表单小部件是 TextInput。 管理员添加了一个 JavaScript 日历和一个“今天”的快捷方式。 包括一个额外的 invalid_date 错误消息密钥。

选项 auto_now_addauto_nowdefault 是互斥的。 这些选项的任何组合都会导致错误。

笔记

按照目前的实施,将 auto_nowauto_now_add 设置为 True 将导致字段设置为 editable=Falseblank=True


笔记

auto_nowauto_now_add 选项将始终使用创建或更新时 默认时区 中的日期。 如果您需要不同的东西,您可能需要考虑简单地使用您自己的可调用默认值或覆盖 save() 而不是使用 auto_nowauto_now_add; 或者使用 DateTimeField 而不是 DateField 并决定如何在显示时间处理从日期时间到日期的转换。


DateTimeField

class DateTimeField(auto_now=False, auto_now_add=False, **options)

日期和时间,在 Python 中由 datetime.datetime 实例表示。 采用与 DateField 相同的额外参数。

此字段的默认表单小部件是单个 TextInput。 管理员使用两个单独的 TextInput 小部件和 JavaScript 快捷方式。


DecimalField

class DecimalField(max_digits=None, decimal_places=None, **options)

一个固定精度的十进制数,在 Python 中由 Decimal 实例表示。 它使用 DecimalValidator 验证输入。

有两个 required 参数:

DecimalField.max_digits
号码中允许的最大位数。 请注意,此数字必须大于或等于 decimal_places
DecimalField.decimal_places
与数字一起存储的小数位数。

例如,要以 2 个小数位的分辨率存储高达 999 的数字,您可以使用:

models.DecimalField(..., max_digits=5, decimal_places=2)

并以 10 位小数的分辨率存储多达约 10 亿的数字:

models.DecimalField(..., max_digits=19, decimal_places=10)

localizeFalseTextInput 时,此字段的默认表单小部件为 NumberInput

笔记

有关两者之间差异的更多信息浮动字段十进制字段类,请看 FloatField 对比 十进制字段 . 您还应该了解十进制字段的 SQLite 限制


DurationField

class DurationField(**options)

用于存储时间段的字段 - 由 timedelta 在 Python 中建模。 在 PostgreSQL 上使用时,使用的数据类型是 interval,而在 Oracle 上,数据类型是 INTERVAL DAY(9) TO SECOND(6)。 否则使用微秒的 bigint

笔记

使用 DurationField 的算术在大多数情况下都有效。 但是,在除 PostgreSQL 之外的所有数据库上,将 DurationField 的值与 DateTimeField 实例上的算术进行比较将无法按预期工作。


EmailField

class EmailField(max_length=254, **options)

CharField 使用 EmailValidator 检查值是否是有效的电子邮件地址。


FileField

class FileField(upload_to=None, max_length=100, **options)

一个文件上传字段

笔记

不支持 primary_key 参数,如果使用会引发错误。


有两个可选参数:

FileField.upload_to

该属性提供了一种设置上传目录和文件名的方式,可以通过两种方式进行设置。 在这两种情况下,值都会传递给 Storage.save() 方法。

如果您指定一个字符串值,它可能包含 strftime() 格式,它将被文件上传的日期/时间替换(这样上传的文件不会填满给定的目录)。 例如:

class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

如果您使用默认的 FileSystemStorage,则字符串值将附加到您的 :setting:`MEDIA_ROOT` 路径以形成本地文件系统上将存储上传文件的位置。 如果您使用不同的存储,请查看该存储的文档以了解它如何处理 upload_to

upload_to 也可以是可调用的,例如函数。 这将被调用以获取上传路径,包括文件名。 这个可调用对象必须接受两个参数并返回要传递给存储系统的 Unix 样式路径(带正斜杠)。 这两个论点是:

参数

描述

instance

定义了 FileField 的模型实例。 更具体地说,这是附加当前文件的特定实例。

在大多数情况下,这个对象还没有被保存到数据库中,所以如果它使用默认的 AutoField,它的主键字段 可能还没有值。

filename

最初赋予文件的文件名。 在确定最终目的地路径时,可能会或可能不会考虑这一点。

例如:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)
FileField.storage
一个存储对象,用于处理文件的存储和检索。 有关如何提供此对象的详细信息,请参阅 管理文件

此字段的默认表单小部件是 ClearableFileInput

在模型中使用 FileFieldImageField(见下文)需要几个步骤:

  1. 在您的设置文件中,您需要将 :setting:`MEDIA_ROOT` 定义为您希望 Django 存储上传文件的目录的完整路径。 (为了性能,这些文件不存储在数据库中。)将 :setting:`MEDIA_URL` 定义为该目录的基本公共 URL。 确保该目录可由 Web 服务器的用户帐户写入。
  2. FileFieldImageField 添加到您的模型中,定义 upload_to 选项以指定要使用的 :setting:`MEDIA_ROOT` 的子目录对于上传的文件。
  3. 所有将存储在您的数据库中的是文件的路径(相对于 :setting:`MEDIA_ROOT`)。 您很可能希望使用 Django 提供的便利 url 属性。 例如,如果您的 ImageField 被称为 mug_shot,您可以使用 模板:Object.mug shot.url 在模板中获取图像的绝对路径。

例如,假设您的 :setting:`MEDIA_ROOT` 设置为 '/home/media',而 upload_to 设置为 'photos/%Y/%m/%d'upload_to'%Y/%m/%d'部分为strftime()格式; '%Y' 是四位数年份,'%m' 是两位数月份,'%d' 是两位数日。 如果您在 1 月上传文件 2007 年 15 月 15 日,它将保存在目录 /home/media/photos/2007/01/15 中。

如果要检索上传文件的磁盘文件名或文件大小,可以分别使用 namesize 属性; 有关可用属性和方法的更多信息,请参阅 File 类参考和 Managing files 主题指南。

笔记

文件在数据库中作为保存模型的一部分,因此在模型被保存之前,不能依赖磁盘上使用的实际文件名。


上传文件的相对 URL 可以通过 url 属性获取。 在内部,这会调用底层 Storage 类的 url() 方法。

请注意,无论何时处理上传的文件,都应密切注意上传文件的位置和文件类型,以避免出现安全漏洞。 验证所有上传的文件,以便您确定这些文件是您认为的那样。 例如,如果您盲目地让某人在未经验证的情况下将文件上传到您的 Web 服务器文档根目录中的目录,那么有人可以上传 CGI 或 PHP 脚本并通过访问其在您站点上的 URL 来执行该脚本。 不允许这样。

另外要注意的是,即使是上传的 HTML 文件,由于可以被浏览器执行(虽然不能被服务器执行),也会造成相当于 XSS 或 CSRF 攻击的安全威胁。

FileField 实例在您的数据库中创建为 varchar 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 max_length 参数更改最大长度。

FileField 和 FieldFile

class FieldFile

当您访问模型上的 FileField 时,您将获得一个 FieldFile 实例作为访问底层文件的代理。

FieldFile 的 API 与 File 的 API 相同,有一个关键区别:类包装的对象不一定是 Python 内置文件对象的包装器。 ] 相反,它是 Storage.open() 方法的结果的包装器,它可能是一个 File 对象,或者它可能是 的自定义存储实现]文件 API。

除了继承自 File 的 API,如 read()write()FieldFile 还包括几个可以用来与底层文件交互的方法:

警告

该类的两个方法save()delete(),默认将关联的FieldFile的模型对象保存在数据库中。


FieldFile.name

文件的名称,包括从相关 FileFieldStorage 的根的相对路径。

FieldFile.size

底层 Storage.size() 方法的结果。

FieldFile.url

通过调用底层 Storage 类的 url() 方法访问文件的相对 URL 的只读属性。

FieldFile.open(mode='rb')

在指定的 mode 中打开或重新打开与此实例关联的文件。 与标准 Python open() 方法不同,它不返回文件描述符。

由于底层文件在访问时是隐式打开的,因此除了重置指向底层文件的指针或更改mode之外,可能没有必要调用此方法。

FieldFile.close()

行为类似于标准 Python file.close() 方法并关闭与此实例关联的文件。

FieldFile.save(name, content, save=True)

此方法获取文件名和文件内容,并将它们传递给字段的存储类,然后将存储的文件与模型字段相关联。 如果您想手动将文件数据与模型上的 FileField 实例相关联,可以使用 save() 方法来保存该文件数据。

接受两个必需的参数:name 是文件名,content 是一个包含文件内容的对象。 可选的 save 参数控制在更改与此字段关联的文件后是否保存模型实例。 默认为 True

请注意, content 参数应该是 django.core.files.File 的实例,而不是 Python 的内置文件对象。 您可以从现有的 Python 文件对象构造一个 File,如下所示:

from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)

或者,您可以从 Python 字符串中构造一个,如下所示:

from django.core.files.base import ContentFile
myfile = ContentFile("hello world")

有关更多信息,请参阅 管理文件

FieldFile.delete(save=True)

删除与此实例关联的文件并清除该字段的所有属性。 注意:如果在调用 delete() 时碰巧打开了该文件,则此方法将关闭该文件。

可选的 save 参数控制在删除与此字段关联的文件后是否保存模型实例。 默认为 True

请注意,删除模型时,不会删除相关文件。 如果您需要清理孤立文件,则需要自己处理(例如,使用自定义管理命令可以手动运行或安排定期运行,例如 cron)。


FilePathField

class FilePathField(path=None, match=None, recursive=False, max_length=100, **options)

A CharField 其选择仅限于文件系统上某个目录中的文件名。 有三个特殊参数,其中第一个是 required

FilePathField.path
必需的。 此 FilePathField 应从中获取其选择的目录的绝对文件系统路径。 示例:"/home/images"
FilePathField.match
可选的。 FilePathField 将用于过滤文件名的正则表达式,作为字符串。 请注意,正则表达式将应用于基本文件名,而不是完整路径。 示例:"foo.*\.txt$",它将匹配名为 foo23.txt 但不匹配 bar.txtfoo23.png 的文件。
FilePathField.recursive
可选的。 TrueFalse。 默认值为 False。 指定是否应包含 path 的所有子目录
FilePathField.allow_files
可选的。 TrueFalse。 默认值为 True。 指定是否应包含指定位置的文件。 此或 allow_folders 必须为 True
FilePathField.allow_folders
可选的。 TrueFalse。 默认值为 False。 指定是否应包括指定位置的文件夹。 此或 allow_files 必须为 True

当然,这些参数可以一起使用。

一个潜在的问题是 match 适用于基本文件名,而不是完整路径。 所以,这个例子:

FilePathField(path="/home/images", match="foo.*", recursive=True)

...将匹配 /home/images/foo.png 但不匹配 /home/images/foo/bar.png,因为 match 适用于基本文件名(foo.pngbar.png)。

FilePathField 实例在您的数据库中创建为 varchar 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 max_length 参数更改最大长度。


FloatField

class FloatField(**options)

Python 中由 float 实例表示的浮点数。

localizeFalseTextInput 时,此字段的默认表单小部件为 NumberInput

FloatField 对比 DecimalField

FloatField 类有时会与 DecimalField 类混淆。 虽然它们都代表实数,但它们代表这些数字的方式不同。 FloatField 在内部使用 Python 的 float 类型,而 DecimalField 使用 Python 的 Decimal 类型。 有关两者之间的区别的信息,请参阅 decimal 模块的 Python 文档。


ImageField

class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)

FileField 继承所有属性和方法,但也验证上传的对象是有效的图像。

除了可用于 FileField 的特殊属性外,ImageField 还具有 heightwidth 属性。

为了方便查询这些属性,ImageField 有两个额外的可选参数:

ImageField.height_field
模型字段的名称,每次保存模型实例时将自动填充图像的高度。
ImageField.width_field
模型字段的名称,每次保存模型实例时将自动填充图像的宽度。

需要 枕头 库。

ImageField 实例在您的数据库中创建为 varchar 列,默认最大长度为 100 个字符。 与其他字段一样,您可以使用 max_length 参数更改最大长度。

此字段的默认表单小部件是 ClearableFileInput


IntegerField

class IntegerField(**options)

一个整数。 从 -21474836482147483647 的值在 Django 支持的所有数据库中都是安全的。

它使用 MinValueValidatorMaxValueValidator 根据默认数据库支持的值验证输入。

localizeFalseTextInput 时,此字段的默认表单小部件为 NumberInput


GenericIPAddressField

class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)

字符串格式的 IPv4 或 IPv6 地址(例如 192.0.2.302a02:42fe::4)。 此字段的默认表单小部件是 TextInput

IPv6 地址规范化遵循 RFC 4291#section-2.2 第 2.2 节,包括使用该节第 3 段中建议的 IPv4 格式,如 ::ffff:192.0.2.0。 例如,2001:0::0:01 将归一化为 2001::1,而 ::ffff:0a0a:0a0a 将归一化为 ::ffff:10.10.10.10。 所有字符都转换为小写。

GenericIPAddressField.protocol
将有效输入限制为指定协议。 可接受的值为 'both'(默认)、'IPv4''IPv6'。 匹配不区分大小写。
GenericIPAddressField.unpack_ipv4
解压缩 IPv4 映射地址,如 ::ffff:192.0.2.1。 如果启用此选项,该地址将被解压缩到 192.0.2.1。 默认为禁用。 仅当 protocol 设置为 'both' 时才能使用。

如果允许空值,就必须允许 null 值,因为空值会被存储为 null。


NullBooleanField

class NullBooleanField(**options)

BooleanFieldnull=True。 使用它而不是这个字段,因为它可能会在 Django 的未来版本中被弃用。


PositiveIntegerField

class PositiveIntegerField(**options)

类似于 IntegerField,但必须为正数或零 (0)。 从 02147483647 的值在 Django 支持的所有数据库中都是安全的。 出于向后兼容性的原因,接受值 0


PositiveSmallIntegerField

class PositiveSmallIntegerField(**options)

PositiveIntegerField,但只允许某个(依赖于数据库的)点下的值。 从 032767 的值在 Django 支持的所有数据库中都是安全的。


SlugField

class SlugField(max_length=50, **options)

Slug 是一个报纸术语。 slug 是某物的短标签,仅包含字母、数字、下划线或连字符。 它们通常用于 URL。

与 CharField 一样,您可以指定 max_length(也请阅读该部分中有关数据库可移植性和 max_length 的说明)。 如果未指定 max_length,Django 将使用默认长度 50。

意味着将 Field.db_index 设置为 True

根据某些其他值的值自动预填充 SlugField 通常很有用。 您可以使用 prepopulated_fields 在管理员中自动执行此操作。

它使用 validate_slugvalidate_unicode_slug 进行验证。

SlugField.allow_unicode
如果是 True,则该字段除 ASCII 字母外还接受 Unicode 字母。 默认为 False


SmallIntegerField

class SmallIntegerField(**options)

类似于 IntegerField,但只允许某个(依赖于数据库的)点下的值。 从 -3276832767 的值在 Django 支持的所有数据库中都是安全的。


TextField

class TextField(**options)

一个大文本字段。 此字段的默认表单小部件是 Textarea

如果您指定 max_length 属性,它将反映在自动生成的表单字段的 Textarea 小部件中。 但是,它不会在模型或数据库级别强制执行。 为此使用 CharField


TimeField

class TimeField(auto_now=False, auto_now_add=False, **options)

时间,在 Python 中由 datetime.time 实例表示。 接受与 DateField 相同的自动填充选项。

此字段的默认表单小部件是 TextInput。 管理员添加了一些 JavaScript 快捷方式。


URLField

class URLField(max_length=200, **options)

URL 的 CharField,由 URLValidator 验证。

此字段的默认表单小部件是 TextInput

与所有 CharField 子类一样,URLField 采用可选的 max_length 参数。 如果未指定 max_length,则使用默认值 200。


UUIDField

class UUIDField(**options)

用于存储通用唯一标识符的字段。 使用 Python 的 UUID 类。 在 PostgreSQL 上使用时,它存储在 uuid 数据类型中,否则存储在 char(32) 中。

对于 primary_key,通用唯一标识符是 AutoField 的一个很好的替代方案。 数据库不会为你生成UUID,所以建议使用default

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

请注意,一个可调用对象(省略括号)被传递给 default,而不是 UUID 的实例。

在 PostgreSQL 上查找

使用 :lookup:`iexact`, :lookup:`contains`, :lookup:`icontains`, :lookup:`startswith`[ X116X]、:lookup:`istartswith`:lookup:`endswith`:lookup:`iendswith` 在 PostgreSQL 上的查找不起作用没有连字符的值,因为 PostgreSQL 将它们存储在带连字符的 uuid 数据类型中。


关系字段

Django 还定义了一组表示关系的字段。

ForeignKey

class ForeignKey(to, on_delete, **options)

多对一的关系。 需要两个位置参数:与模型相关的类和 on_delete 选项。

要创建递归关系——一个与自身具有多对一关系的对象——使用 models.ForeignKey('self', on_delete=models.CASCADE)

如果需要在尚未定义的模型上创建关系,可以使用模型的名称,而不是模型对象本身:

from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'Manufacturer',
        on_delete=models.CASCADE,
    )
    # ...

class Manufacturer(models.Model):
    # ...
    pass

当模型被子类化为具体模型并且与抽象模型的 app_label 无关时,在 抽象模型 上以这种方式定义的关系会得到解析:

products/models.py

from django.db import models

class AbstractCar(models.Model):
    manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)

    class Meta:
        abstract = True

production/models.py

from django.db import models
from products.models import AbstractCar

class Manufacturer(models.Model):
    pass

class Car(AbstractCar):
    pass

# Car.manufacturer will point to `production.Manufacturer` here.

要引用在另一个应用程序中定义的模型,您可以明确指定具有完整应用程序标签的模型。 例如,如果上面的 Manufacturer 模型是在另一个名为 production 的应用程序中定义的,则您需要使用:

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
    )

这种被称为懒惰关系的引用,在解决两个应用程序之间的循环导入依赖关系时很有用。

ForeignKey 上自动创建数据库索引。 您可以通过将 db_index 设置为 False 来禁用此功能。 如果您创建外键是为了一致性而不是连接,或者您将创建替代索引(如部分或多列索引),您可能希望避免索引的开销。

数据库表现

在幕后,Django 将 "_id" 附加到字段名称以创建其数据库列名称。 在上面的例子中,Car 模型的数据库表将有一个 manufacturer_id 列。 (您可以通过指定 db_column 来显式更改此设置)但是,除非您编写自定义 SQL,否则您的代码永远不必处理数据库列名。 您将始终处理模型对象的字段名称。


参数

ForeignKey 接受定义关系如何工作的细节的其他参数。

ForeignKey.on_delete

ForeignKey 引用的对象被删除时,Django 将模拟由 on_delete 参数指定的 SQL 约束的行为。 例如,如果您有一个可以为 null 的 ForeignKey 并且您希望在删除引用的对象时将其设置为 null:

user = models.ForeignKey(
    User,
    models.SET_NULL,
    blank=True,
    null=True,
)

on_delete 不会在数据库中创建 SQL 约束。 支持数据库级级联选项 :ticket:`可能会在以后实施 <21961>` .

on_delete 的可能值在 django.db.models 中找到:

  • CASCADE

    级联删除。 Django 模拟 SQL 约束 ON DELETE CASCADE 的行为,并删除包含 ForeignKey 的对象。

    Model.delete() 不会在相关模型上调用,但会为所有已删除的对象发送 pre_deletepost_delete 信号。

  • PROTECT

    通过引发 ProtectedErrordjango.db.IntegrityError 的子类)来防止删除引用的对象。

  • SET_NULL

    设置 ForeignKey 为空; 这仅在 nullTrue 时才有可能。

  • SET_DEFAULT

    ForeignKey 设置为其默认值; 必须设置 ForeignKey 的默认值。

  • SET()

    ForeignKey 设置为传递给 SET() 的值,或者如果传入的是 callable,则为调用它的结果。 在大多数情况下,需要传递一个可调用对象以避免在导入 models.py 时执行查询:

    from django.conf import settings
    from django.contrib.auth import get_user_model
    from django.db import models
    
    def get_sentinel_user():
        return get_user_model().objects.get_or_create(username='deleted')[0]
    
    class MyModel(models.Model):
        user = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            on_delete=models.SET(get_sentinel_user),
        )
  • DO_NOTHING

    不采取行动。 如果您的数据库后端强制执行参照完整性,除非您手动向数据库字段添加 SQL ON DELETE 约束,否则这将导致 IntegrityError

ForeignKey.limit_choices_to

当使用 ModelForm 或管理员呈现此字段时,为该字段的可用选项设置限制(默认情况下,查询集中的所有对象都可供选择)。 可以使用字典、Q 对象或返回字典或 Q 对象的可调用对象。

例如:

staff_member = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    limit_choices_to={'is_staff': True},
)

导致 ModelForm 上的相应字段仅列出具有 is_staff=TrueUsers。 这可能对 Django 管理员有所帮助。

例如,当与 Python datetime 模块结合使用以按日期范围限制选择时,可调用表单会很有帮助。 例如:

def limit_pub_date_choices():
    return {'pub_date__lte': datetime.date.utcnow()}

limit_choices_to = limit_pub_date_choices

如果 limit_choices_to 是或返回一个 Q 对象 ,这对 复杂查询 很有用,那么它只会影响 admin 中可用的选项未在该模型的 ModelAdmin 中的 raw_id_fields 中列出。

笔记

如果可调用对象用于 limit_choices_to,则每次实例化新表单时都会调用它。 它也可以在模型被验证时调用,例如通过管理命令或管理员。 管理员构建查询集以在各种边缘情况下多次验证其表单输入,因此您的可调用对象可能会被多次调用。

ForeignKey.related_name

用于从相关对象返回到此对象的关系的名称。 它也是 related_query_name(用于来自目标模型的反向过滤器名称的名称)的默认值。 有关完整说明和示例,请参阅 相关对象文档 。 注意在抽象模型上定义关系时必须设置这个值; 当你这样做时 一些特殊的语法 可用。

如果您不希望 Django 创建反向关系,请将 related_name 设置为 '+' 或以 '+' 结束。 例如,这将确保 User 模型不会与此模型具有向后关系:

user = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    related_name='+',
)
ForeignKey.related_query_name

用于来自目标模型的反向过滤器名称的名称。 如果设置,则默认为 related_namedefault_related_name 的值,否则默认为模型名称:

# Declare the ForeignKey with related_query_name
class Tag(models.Model):
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name="tags",
        related_query_name="tag",
    )
    name = models.CharField(max_length=255)

# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")

related_name一样,related_query_name通过一些特殊语法支持应用标签和类插值。

ForeignKey.to_field
关系所指向的相关对象上的字段。 默认情况下,Django 使用相关对象的主键。 如果您引用不同的字段,则该字段必须具有 unique=True
ForeignKey.db_constraint

控制是否应在数据库中为此外键创建约束。 默认值为 True,这几乎肯定是您想要的; 将此设置为 False 可能对数据完整性非常不利。 也就是说,以下是您可能想要执行此操作的一些场景:

  • 你有无效的冗余数据

  • 您正在对数据库进行分片。

如果将其设置为 False,则访问不存在的相关对象将引发其 DoesNotExist 异常。

ForeignKey.swappable

如果此 ForeignKey 指向可交换模型,则控制迁移框架的反应。 如果它是 True - 默认值 - 那么如果 ForeignKey 指向与 settings.AUTH_USER_MODEL(或其他可交换模型设置)的当前值匹配的模型,则关系将使用对设置的引用而不是直接对模型的引用存储在迁移中。

如果您确定您的模型应始终指向换入模型,您只想将其覆盖为 False - 例如,如果它是专为您的自定义用户模型设计的配置文件模型。

将其设置为 False 并不意味着您可以引用可交换模型,即使它被换出 - False 只是意味着使用此 ForeignKey 进行的迁移将始终引用您指定的确切模型(因此例如,如果用户尝试使用您不支持的 User 模型运行,它将很难失败)。

如果有疑问,请将其保留为默认值 True


ManyToManyField

class ManyToManyField(to, **options)

多对多的关系。 需要一个位置参数:与模型相关的类,其工作方式与 ForeignKey 完全相同,包括 recursivelazy 关系。

可以使用字段的 RelatedManager 添加、删除或创建相关对象。

数据库表现

在幕后,Django 创建了一个中间连接表来表示多对多关系。 默认情况下,此表名称是使用多对多字段的名称和包含它的模型的表名称生成的。 由于某些数据库不支持超过一定长度的表名,这些表名将被自动截断并使用唯一性哈希,例如 author_books_9cdf。 您可以使用 db_table 选项手动提供连接表的名称。


参数

ManyToManyField 接受一组额外的参数——都是可选的——控制关系如何运作。

ManyToManyField.related_name
ForeignKey.related_name 相同。
ManyToManyField.related_query_name
ForeignKey.related_query_name 相同。
ManyToManyField.limit_choices_to

ForeignKey.limit_choices_to 相同。

limit_choices_to 在使用 参数指定的自定义中间表的 ManyToManyField 上使用时无效。

ManyToManyField.symmetrical

仅用于对 self 的 ManyToManyFields 的定义。 考虑以下模型:

from django.db import models

class Person(models.Model):
    friends = models.ManyToManyField("self")

当 Django 处理这个模型时,它识别出它自己有一个 ManyToManyField,因此它不会向 Person 类添加 person_set 属性。 相反,假设 ManyToManyField 是对称的——也就是说,如果我是你的朋友,那么你就是我的朋友。

如果您不想在与 self 的多对多关系中对称,请将 symmetrical 设置为 False。 这将强制 Django 添加反向关系的描述符,允许 ManyToManyField 关系是非对称的。

ManyToManyField.through

Django 会自动生成一张表来管理多对多关系。 但是,如果要手动指定中间表,则可以使用 选项指定代表要使用的中间表的 Django 模型。

此选项最常见的用途是将 额外数据与多对多关系 相关联。

如果您不指定显式 through 模型,仍然有一个隐式 through 模型类,您可以使用它直接访问为保存关联而创建的表。 它有三个字段来链接模型。

如果源模型和目标模型不同,则会生成以下字段:

  • id:关系的主键。

  • <containing_model>_id:声明ManyToManyField的型号的id

  • <other_model>_idManyToManyField指向的型号的id

如果 ManyToManyField 指向和指向同一模型,则会生成以下字段:

  • id:关系的主键。

  • from_<model>_id:指向模型的实例的id(即 源实例)。

  • to_<model>_id:关系指向的实例的id(即 目标模型实例)。

这个类可以像普通模型一样,用于查询给定模型实例的关联记录:

ManyToManyField.through_fields

仅在指定自定义中介模型时使用。 Django 通常会确定使用中间模型的哪些字段以自动建立多对多关系。 但是,请考虑以下模型:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(
        Person,
        through='Membership',
        through_fields=('group', 'person'),
    )

class Membership(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    inviter = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        related_name="membership_invites",
    )
    invite_reason = models.CharField(max_length=64)

Membership两个外键到Personpersoninviter),这使得关系模糊,Django无法知道使用哪一个。 在这种情况下,您必须使用 through_fields 明确指定 Django 应该使用哪些外键,如上例所示。

through_fields 接受一个二元组 ('field1', 'field2'),其中 field1 是模型的外键名称 ManyToManyField 在 (group 在这种情况下),以及 field2 目标模型的外键名称(在这种情况下为 person)。

当您在一个中间模型上有多个外键指向参与多对多关系的任何(甚至两个)模型时,您 必须 指定 through_fields。 这也适用于 递归关系 当使用中间模型并且模型有两个以上的外键时,或者您想明确指定应该使用哪两个 Django。

使用中间模型的递归关系总是被定义为非对称的——也就是说,对称=假——因此,存在“源”和“目标”的概念。 在这种情况下,'field1' 将被视为关系的“源”,而 'field2' 将被视为“目标”。

ManyToManyField.db_table
要创建的用于存储多对多数据的表的名称。 如果未提供,Django 将假定基于以下名称的默认名称:定义关系的模型表和字段本身的名称。
ManyToManyField.db_constraint

控制是否应在数据库中为中间表中的外键创建约束。 默认值为 True,这几乎肯定是您想要的; 将此设置为 False 可能对数据完整性非常不利。 也就是说,以下是您可能想要执行此操作的一些场景:

  • 你有无效的冗余数据

  • 您正在对数据库进行分片。

通过 db_constraintthrough 都是错误的。

ManyToManyField.swappable

如果此 ManyToManyField 指向可交换模型,则控制迁移框架的反应。 如果它是 True - 默认值 - 那么如果 ManyToManyField 指向的模型与 settings.AUTH_USER_MODEL(或其他可交换模型设置)的当前值匹配,则该关系将使用对设置的引用而不是直接对模型的引用存储在迁移中。

如果您确定您的模型应始终指向换入模型,您只想将其覆盖为 False - 例如,如果它是专为您的自定义用户模型设计的配置文件模型。

如果有疑问,请将其保留为默认值 True

ManyToManyField 不支持 验证器

null 不起作用,因为无法在数据库级别要求关系。


OneToOneField

class OneToOneField(to, on_delete, parent_link=False, **options)

一对一的关系。 从概念上讲,这类似于具有 unique=TrueForeignKey,但关系的“反向”侧将直接返回单个对象。

这是作为模型的主键最有用的,它以某种方式“扩展”了另一个模型; 多表继承例如通过添加从子模型到父模型的隐式一对一关系来实现。

需要一个位置参数:与模型相关的类。 这与 ForeignKey 的工作方式完全相同,包括所有关于 recursivelazy 关系的选项。

如果您没有为 OneToOneField 指定 related_name 参数,Django 将使用当前模型的小写名称作为默认值。

使用以下示例:

from django.conf import settings
from django.db import models

class MySpecialUser(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    supervisor = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='supervisor_of',
    )

您生成的 User 模型将具有以下属性:

>>> user = User.objects.get(pk=1)
>>> hasattr(user, 'myspecialuser')
True
>>> hasattr(user, 'supervisor_of')
True

如果相关表中的条目不存在,则在访问反向关系时会引发 DoesNotExist 异常。 例如,如果用户没有由 MySpecialUser 指定的主管:

>>> user.supervisor_of
Traceback (most recent call last):
    ...
DoesNotExist: User matching query does not exist.

此外, OneToOneField 接受 ForeignKey 接受的所有额外参数,以及一个额外参数:

OneToOneField.parent_link
True 用于从另一个 具体模型 继承的模型中时,表明该字段应用作返回父类的链接,而不是额外的 OneToOneField ] 通常由子类化隐式创建。

有关 OneToOneField 的使用示例,请参阅 一对一关系


字段 API 参考

class Field

Field 是代表数据库表列的抽象类。 Django 使用字段来创建数据库表 (db_type()),将 Python 类型映射到数据库 (get_prep_value()),反之亦然 (from_db_value() ])。

因此,字段是不同 Django API 中的基本部分,尤其是 modelsquerysets

在模型中,字段被实例化为类属性并表示特定的表列,请参阅 Models。 它具有 nullunique 等属性,以及 Django 用于将字段值映射到数据库特定值的方法。

FieldRegisterLookupMixin 的子类,因此 TransformLookup 都可以在其上注册以用于 QuerySet ]s(例如 field_name__exact="foo")。 默认情况下已注册所有 内置查找

Django 的所有内置字段,例如 CharField,都是 Field 的特定实现。 如果您需要自定义字段,您可以对任何内置字段进行子类化,也可以从头开始编写 Field。 无论哪种情况,请参阅 编写自定义模型字段

description

字段的详细描述,例如 对于 django.contrib.admindocs 应用程序。

描述可以是以下形式:

description = _("String (up to %(max_length)s)")

其中参数是从字段的 __dict__ 插入的。

要将 Field 映射到特定于数据库的类型,Django 公开了几种方法:

get_internal_type()

返回命名此字段的字符串以用于后端特定目的。 默认情况下,它返回类名。

有关自定义字段的用法,请参阅 模拟内置字段类型

db_type(connection)

返回 字段 的数据库列数据类型,同时考虑 connection

有关自定义字段中的用法,请参阅 自定义数据库类型

rel_db_type(connection)

返回指向 字段ForeignKeyOneToOneField 等字段的数据库列数据类型,同时考虑 connection

有关自定义字段中的用法,请参阅 自定义数据库类型

Django 主要有三种情况需要与数据库后台和字段进行交互。

  • 当它查询数据库时(Python 值 -> 数据库后台值)

  • 当它从数据库中加载数据时(数据库后台值 -> Python 值)

  • 当它保存到数据库时(Python 值 -> 数据库后端值)

查询时使用get_db_prep_value()get_prep_value()

get_prep_value(value)

value 是模型属性的当前值,该方法应以已准备好用作查询中的参数的格式返回数据。

有关用法,请参阅 将 Python 对象转换为查询值

get_db_prep_value(value, connection, prepared=False)

value 转换为后端特定的值。 默认情况下,如果 prepared=Trueget_prep_value() 如果是 False,它会返回 value

有关用法,请参阅 将查询值转换为数据库值

加载数据时,使用from_db_value()

from_db_value(value, expression, connection)

将数据库返回的值转换为 Python 对象。 与 get_prep_value() 相反。

这个方法不用于大多数内置字段,因为数据库后端已经返回了正确的 Python 类型,或者后端自己进行了转换。

有关用法,请参阅 将值转换为 Python 对象

笔记

出于性能原因,from_db_value 没有在不需要它的字段(所有 Django 字段)上实现为无操作。 因此,您不能在定义中调用 super

保存时使用pre_save()get_db_prep_save()

get_db_prep_save(value, connection)

get_db_prep_value() 相同,但在字段值必须 saved 到数据库时调用。 默认返回 get_db_prep_value()

pre_save(model_instance, add)

get_db_prep_save() 之前调用的方法在保存之前准备值(例如 对于 DateField.auto_now)。

model_instance为该字段所属的实例,add为该实例是否第一次存入数据库。

它应该从 model_instance 为该字段返回适当属性的值。 属性名称在 self.attname 中(这是由 Field 设置的)。

请参阅 保存前的预处理值 以了解用法。

字段经常以不同的类型接收它们的值,要么来自序列化,要么来自表单。

to_python(value)

将值转换为正确的 Python 对象。 它的作用与 value_to_string() 的相反,也在 clean() 中调用。

有关用法,请参阅 将值转换为 Python 对象

除了保存到数据库,字段还需要知道如何将其值序列化。

value_from_object(obj)

返回给定模型实例的字段值。

这个方法经常被 value_to_string() 使用。

value_to_string(obj)

obj 转换为字符串。 用于序列化字段的值。

有关用法,请参阅 转换字段数据以进行序列化

当使用模型表单时,Field需要知道它应该用哪个表单字段表示:

formfield(form_class=None, choices_form_class=None, **kwargs)

ModelForm 返回此字段的默认 django.forms.Field

默认情况下,如果 form_classchoices_form_class 都是 None,则使用 CharField。 如果该字段具有 choices 且未指定 choices_form_class,则使用 TypedChoiceField

有关用法,请参阅 指定模型字段的表单字段

deconstruct()

返回一个包含足够信息的四元元组来重新创建字段。

  1. 模型上的字段名称。

  2. 字段的导入路径(例如 "django.db.models.IntegerField")。 这应该是最便携的版本,所以不那么具体可能会更好。

  3. 一个位置参数的列表。

  4. 一个关键字参数的字典。

必须将此方法添加到 1.7 之前的字段中才能使用 Migrations 迁移其数据。


字段属性参考

每个 Field 实例都包含几个允许自省其行为的属性。 当您需要编写依赖于字段功能的代码时,请使用这些属性而不是 isinstance 检查。 这些属性可以与 Model._meta API 一起使用,以缩小特定字段类型的搜索范围。 自定义模型字段应实现这些标志。

字段的属性

Field.auto_created
指示字段是否自动创建的布尔标志,例如模型继承使用的 OneToOneField
Field.concrete
布尔值标志,表示该字段是否有与之相关的数据库列。
Field.hidden

布尔标志,指示一个字段是否用于支持另一个非隐藏字段的功能(例如 content_typeobject_id 字段组成 GenericForeignKey)。 hidden 标志用于区分模型上字段的公共子集与模型上的所有字段。

笔记

Options.get_fields() 默认排除隐藏字段。 传入 include_hidden=True 返回结果中的隐藏字段。

Field.is_relation
指示字段是否包含对其功能的一个或多个其他模型的引用的布尔标志(例如 ForeignKeyManyToManyFieldOneToOneField 等)。
Field.model
返回定义字段的模型。 如果在模型的超类上定义了字段,则 model 将引用超类,而不是实例的类。


有关系的字段的属性

这些属性用于查询关系的基数和其他详细信息。 这些属性存在于所有字段中; 但是,如果字段是关系类型 (Field.is_relation=True),它们将只有布尔值(而不是 None)。

Field.many_to_many
如果字段具有多对多关系,则布尔标志为 TrueFalse 否则。 Django 中唯一包含 True 的字段是 ManyToManyField
Field.many_to_one
如果字段具有多对一关系,则为 True 的布尔标志,例如 ForeignKeyFalse 否则。
Field.one_to_many
如果字段具有一对多关系,则布尔标志为 True,例如 GenericRelationForeignKey 的反向; False 否则。
Field.one_to_one
如果字段具有一对一关系,则为 True 的布尔标志,例如 OneToOneFieldFalse 否则。
Field.related_model
指向与该字段相关的模型。 例如,ForeignKey(Author, on_delete=models.CASCADE) 中的 AuthorGenericForeignKeyrelated_model 始终为 None