{"title":"模型","version":"2.0","locale":"zh-hans","docname":"topics/db/models","url":"/zh-hans/2.0/topics/db/models/","canonical":"https://djangodocs.dev/zh-hans/2.0/topics/db/models/","summary":"模型是您的数据唯一而且准确的信息来源。它包含您正在储存的数据的重要字段和行为。一般来说，每一个模型都映射一个数据库表。","html":"<span id=\"models\"></span><h1>模型<a class=\"heading-anchor\" href=\"#module-django.db.models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>模型是您的数据唯一而且准确的信息来源。它包含您正在储存的数据的重要字段和行为。一般来说，每一个模型都映射一个数据库表。</p>\n<p>基础：</p>\n<ul class=\"simple\">\n<li><p>每个模型都是一个 Python 的类，这些类继承 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model\" title=\"django.db.models.Model\"><code class=\"xref py py-class docutils literal notranslate\">django.db.models.Model</code></a></p></li>\n<li><p>模型类的每个属性都相当于一个数据库的字段。</p></li>\n<li><p>综上诉说，Django 给你一个自动生成访问数据库的 API；请参阅 <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/\"><span class=\"doc\">Making queries</span></a>。</p></li>\n</ul>\n<section id=\"quick-example\">\n<h2>快速上手<a class=\"heading-anchor\" href=\"#quick-example\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>这个样例模型定义了一个 <code class=\"docutils literal notranslate\">Person</code>, 其拥有 <code class=\"docutils literal notranslate\">first_name</code> 和 <code class=\"docutils literal notranslate\">last_name</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n    last_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n</code></pre></div>\n<p><code class=\"docutils literal notranslate\">first_name</code> 和 <code class=\"docutils literal notranslate\">last_name</code> <a class=\"reference internal\" href=\"#fields\">是模型的字段</a>。每个字段都被指定为一个类属性，并且每个属性映射为一个数据库列。</p>\n<p>上面的 <code class=\"docutils literal notranslate\">Person</code> 模型会创建一个如下的数据库表：</p>\n<div class=\"code-block\" data-language=\"sql\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">SQL</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"SQL code\"><code><span class=\"k\">CREATE</span> <span class=\"k\">TABLE</span> myapp_person <span class=\"p\">(</span>\n    <span class=\"ss\">&quot;id&quot;</span> <span class=\"nb\">serial</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span> <span class=\"k\">PRIMARY</span> <span class=\"k\">KEY</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;first_name&quot;</span> <span class=\"nb\">varchar</span><span class=\"p\">(</span><span class=\"mi\">30</span><span class=\"p\">)</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;last_name&quot;</span> <span class=\"nb\">varchar</span><span class=\"p\">(</span><span class=\"mi\">30</span><span class=\"p\">)</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span>\n<span class=\"p\">);</span>\n</code></pre></div>\n<p>一些技术上的说明：</p>\n<ul class=\"simple\">\n<li><p>该表的名称 “myapp_person” 是自动从某些模型元数据中派生出来，但可以被改写。有关更多详细信息，请参阅：<span class=\"xref std std-ref\">表命名</span>。</p></li>\n<li><p>一个 <code class=\"docutils literal notranslate\">id</code> 字段会被自动添加，但是这种行为可以被改写。请参阅：<span class=\"xref std std-ref\">默认主键字段</span>。</p></li>\n<li><p>The <code class=\"docutils literal notranslate\">CREATE TABLE</code> SQL in this example is formatted using PostgreSQL\nsyntax, but it's worth noting Django uses SQL tailored to the database\nbackend specified in your <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/settings/\"><span class=\"doc\">settings file</span></a>.</p></li>\n</ul>\n</section>\n<section id=\"using-models\">\n<h2>使用模型<a class=\"heading-anchor\" href=\"#using-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>一旦你定义了你的模型，你需要告诉 Django 你准备*使用*这些模型。你需要修改设置文件中的 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> ，在这个设置中添加包含你  <code class=\"docutils literal notranslate\">models.py</code> 文件的模块的名字。</p>\n<p>例如，如果模型位于你项目中的``myapp.models``中（ 此包结构使用:djadmin:manage.py startapp`命令创建），:setting:`INSTALLED_APPS 应设置如下:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>INSTALLED_APPS <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"c1\">#...</span>\n    <span class=\"s1\">&#39;myapp&#39;</span><span class=\"p\">,</span>\n    <span class=\"c1\">#...</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>When you add new apps to <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a>, be sure to run\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">manage.py migrate</code></a>, optionally making migrations\nfor them first with <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\">manage.py makemigrations</code></a>.</p>\n</section>\n<section id=\"fields\">\n<h2>字段<a class=\"heading-anchor\" href=\"#fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>模型中最重要的、并且也是唯一必须的是数据库的字段定义。字段在类中定义。定义字段名时应小心避免使用与 <span class=\"xref std std-doc\">models API&lt;/ref/models/instances&gt;冲突的名称， 如 ``clean`</span>, <code class=\"docutils literal notranslate\">save</code>, or <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>delete``等.</p>\n<p>举例：</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Musician</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    last_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    instrument <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Album</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    artist <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>Musician<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">)</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n    release_date <span class=\"o\">=</span> models<span class=\"o\">.</span>DateField<span class=\"p\">()</span>\n    num_stars <span class=\"o\">=</span> models<span class=\"o\">.</span>IntegerField<span class=\"p\">()</span>\n</code></pre></div>\n<section id=\"field-types\">\n<h3>字段类型<a class=\"heading-anchor\" href=\"#field-types\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Each field in your model should be an instance of the appropriate\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> class. Django uses the field class types to\ndetermine a few things:</p>\n<ul class=\"simple\">\n<li><p>字段类型用以指定数据库数据类型（如：<code class=\"docutils literal notranslate\">INTEGER</code>, <code class=\"docutils literal notranslate\">VARCHAR</code>, <code class=\"docutils literal notranslate\">TEXT</code>）</p></li>\n<li><p>默认的HTML表单输入框&lt;/ref/forms/widgets&gt;（如：&lt;input type=&quot;text&quot;&gt;&lt;select&gt;）</p></li>\n<li><p>用于Django admin和自动生成表单的基本验证。</p></li>\n</ul>\n<p>Django内置了多种字段类型；你可以在模型字段参考&lt;model-field-types&gt;中看到完整列表。如果Django内置类型不能满足你的需求，你可以很轻松地编写自定义的字段类型；见:doc:/howto/custom-model-fields。</p>\n</section>\n<section id=\"field-options\">\n<h3>Field options<a class=\"heading-anchor\" href=\"#field-options\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Each field takes a certain set of field-specific arguments (documented in the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#model-field-types\"><span class=\"std std-ref\">model field reference</span></a>). For example,\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.CharField\" title=\"django.db.models.CharField\"><code class=\"xref py py-class docutils literal notranslate\">CharField</code></a> (and its subclasses) require a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.CharField.max_length\" title=\"django.db.models.CharField.max_length\"><code class=\"xref py py-attr docutils literal notranslate\">max_length</code></a> argument which specifies the size\nof the <code class=\"docutils literal notranslate\">VARCHAR</code> database field used to store the data.</p>\n<p>There's also a set of common arguments available to all field types. All are\noptional. They're fully explained in the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#common-model-field-options\"><span class=\"std std-ref\">reference</span></a>, but here's a quick summary of the most often-used\nones:</p>\n<dl>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.null\" title=\"django.db.models.Field.null\"><code class=\"xref py py-attr docutils literal notranslate\">null</code></a></dt><dd><p>If <code class=\"docutils literal notranslate\">True</code>, Django will store empty values as <code class=\"docutils literal notranslate\">NULL</code> in the database.\nDefault is <code class=\"docutils literal notranslate\">False</code>.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.blank\" title=\"django.db.models.Field.blank\"><code class=\"xref py py-attr docutils literal notranslate\">blank</code></a></dt><dd><p>If <code class=\"docutils literal notranslate\">True</code>, the field is allowed to be blank. Default is <code class=\"docutils literal notranslate\">False</code>.</p>\n<p>Note that this is different than <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.null\" title=\"django.db.models.Field.null\"><code class=\"xref py py-attr docutils literal notranslate\">null</code></a>.\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.null\" title=\"django.db.models.Field.null\"><code class=\"xref py py-attr docutils literal notranslate\">null</code></a> is purely database-related, whereas\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.blank\" title=\"django.db.models.Field.blank\"><code class=\"xref py py-attr docutils literal notranslate\">blank</code></a> is validation-related. If a field has\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.blank\" title=\"django.db.models.Field.blank\"><code class=\"xref py py-attr docutils literal notranslate\">blank=True</code></a>, form validation will\nallow entry of an empty value. If a field has <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.blank\" title=\"django.db.models.Field.blank\"><code class=\"xref py py-attr docutils literal notranslate\">blank=False</code></a>, the field will be required.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.choices\" title=\"django.db.models.Field.choices\"><code class=\"xref py py-attr docutils literal notranslate\">choices</code></a></dt><dd><p>An iterable (e.g., a list or tuple) of 2-tuples to use as choices for\nthis field. If this is given, the default form widget will be a select box\ninstead of the standard text field and will limit choices to the choices\ngiven.</p>\n<p>A choices list looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>YEAR_IN_SCHOOL_CHOICES <span class=\"o\">=</span> <span class=\"p\">(</span>\n    <span class=\"p\">(</span><span class=\"s1\">&#39;FR&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Freshman&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">(</span><span class=\"s1\">&#39;SO&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Sophomore&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">(</span><span class=\"s1\">&#39;JR&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Junior&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">(</span><span class=\"s1\">&#39;SR&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Senior&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">(</span><span class=\"s1\">&#39;GR&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Graduate&#39;</span><span class=\"p\">),</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>The first element in each tuple is the value that will be stored in the\ndatabase. The second element is displayed by the field's form widget.</p>\n<p>Given a model instance, the display value for a field with <code class=\"docutils literal notranslate\">choices</code> can\nbe accessed using the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.get_FOO_display\" title=\"django.db.models.Model.get_FOO_display\"><code class=\"xref py py-meth docutils literal notranslate\">get_FOO_display()</code></a>\nmethod. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    SHIRT_SIZES <span class=\"o\">=</span> <span class=\"p\">(</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;S&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Small&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;M&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Medium&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"s1\">&#39;L&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Large&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">)</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">60</span><span class=\"p\">)</span>\n    shirt_size <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">,</span> choices<span class=\"o\">=</span>SHIRT_SIZES<span class=\"p\">)</span>\n</code></pre></div>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>p <span class=\"o\">=</span> Person<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Fred Flintstone&quot;</span><span class=\"p\">,</span> shirt_size<span class=\"o\">=</span><span class=\"s2\">&quot;L&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>shirt_size\n<span class=\"go\">&#39;L&#39;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>get_shirt_size_display<span class=\"p\">()</span>\n<span class=\"go\">&#39;Large&#39;</span>\n</code></pre></div>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.default\" title=\"django.db.models.Field.default\"><code class=\"xref py py-attr docutils literal notranslate\">default</code></a></dt><dd><p>The default value for the field. This can be a value or a callable\nobject. If callable it will be called every time a new object is\ncreated.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.help_text\" title=\"django.db.models.Field.help_text\"><code class=\"xref py py-attr docutils literal notranslate\">help_text</code></a></dt><dd><p>Extra &quot;help&quot; text to be displayed with the form widget. It's useful for\ndocumentation even if your field isn't used on a form.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key</code></a></dt><dd><p>If <code class=\"docutils literal notranslate\">True</code>, this field is the primary key for the model.</p>\n<p>If you don't specify <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key=True</code></a> for\nany fields in your model, Django will automatically add an\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.IntegerField\" title=\"django.db.models.IntegerField\"><code class=\"xref py py-class docutils literal notranslate\">IntegerField</code></a> to hold the primary key, so you don't need to set\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key=True</code></a> on any of your fields\nunless you want to override the default primary-key behavior. For more,\nsee <a class=\"reference internal\" href=\"#automatic-primary-key-fields\"><span class=\"std std-ref\">Automatic primary key fields</span></a>.</p>\n<p>The primary key field is read-only. If you change the value of the primary\nkey on an existing object and then save it, a new object will be created\nalongside the old one. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Fruit</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">,</span> primary_key<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n</code></pre></div>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>fruit <span class=\"o\">=</span> Fruit<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s1\">&#39;Apple&#39;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>fruit<span class=\"o\">.</span>name <span class=\"o\">=</span> <span class=\"s1\">&#39;Pear&#39;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>fruit<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Fruit<span class=\"o\">.</span>objects<span class=\"o\">.</span>values_list<span class=\"p\">(</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">,</span> flat<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;QuerySet [&#39;Apple&#39;, &#39;Pear&#39;]&gt;</span>\n</code></pre></div>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.unique\" title=\"django.db.models.Field.unique\"><code class=\"xref py py-attr docutils literal notranslate\">unique</code></a></dt><dd><p>If <code class=\"docutils literal notranslate\">True</code>, this field must be unique throughout the table.</p>\n</dd>\n</dl>\n<p>Again, these are just short descriptions of the most common field options. Full\ndetails can be found in the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#common-model-field-options\"><span class=\"std std-ref\">common model field option reference</span></a>.</p>\n</section>\n<section id=\"automatic-primary-key-fields\">\n<span id=\"id1\"></span><h3>Automatic primary key fields<a class=\"heading-anchor\" href=\"#automatic-primary-key-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>By default, Django gives each model the following field:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"nb\">id</span> <span class=\"o\">=</span> models<span class=\"o\">.</span>AutoField<span class=\"p\">(</span>primary_key<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>This is an auto-incrementing primary key.</p>\n<p>If you'd like to specify a custom primary key, just specify\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key=True</code></a> on one of your fields. If Django\nsees you've explicitly set <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">Field.primary_key</code></a>, it won't add the automatic\n<code class=\"docutils literal notranslate\">id</code> column.</p>\n<p>Each model requires exactly one field to have <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key=True</code></a> (either explicitly declared or automatically added).</p>\n</section>\n<section id=\"verbose-field-names\">\n<span id=\"id2\"></span><h3>Verbose field names<a class=\"heading-anchor\" href=\"#verbose-field-names\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Each field type, except for <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a>,\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a>, takes an optional first positional\nargument -- a verbose name. If the verbose name isn't given, Django will\nautomatically create it using the field's attribute name, converting underscores\nto spaces.</p>\n<p>In this example, the verbose name is <code class=\"docutils literal notranslate\">&quot;person's first name&quot;</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span><span class=\"s2\">&quot;person&#39;s first name&quot;</span><span class=\"p\">,</span> max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>In this example, the verbose name is <code class=\"docutils literal notranslate\">&quot;first name&quot;</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a>,\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> require the first argument to be a\nmodel class, so use the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.verbose_name\" title=\"django.db.models.Field.verbose_name\"><code class=\"xref py py-attr docutils literal notranslate\">verbose_name</code></a> keyword argument:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>poll <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>\n    Poll<span class=\"p\">,</span>\n    on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span>\n    verbose_name<span class=\"o\">=</span><span class=\"s2\">&quot;the related poll&quot;</span><span class=\"p\">,</span>\n<span class=\"p\">)</span>\nsites <span class=\"o\">=</span> models<span class=\"o\">.</span>ManyToManyField<span class=\"p\">(</span>Site<span class=\"p\">,</span> verbose_name<span class=\"o\">=</span><span class=\"s2\">&quot;list of sites&quot;</span><span class=\"p\">)</span>\nplace <span class=\"o\">=</span> models<span class=\"o\">.</span>OneToOneField<span class=\"p\">(</span>\n    Place<span class=\"p\">,</span>\n    on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span>\n    verbose_name<span class=\"o\">=</span><span class=\"s2\">&quot;related place&quot;</span><span class=\"p\">,</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>The convention is not to capitalize the first letter of the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.verbose_name\" title=\"django.db.models.Field.verbose_name\"><code class=\"xref py py-attr docutils literal notranslate\">verbose_name</code></a>. Django will automatically capitalize the first\nletter where it needs to.</p>\n</section>\n<section id=\"relationships\">\n<h3>Relationships<a class=\"heading-anchor\" href=\"#relationships\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Clearly, the power of relational databases lies in relating tables to each\nother. Django offers ways to define the three most common types of database\nrelationships: many-to-one, many-to-many and one-to-one.</p>\n<section id=\"many-to-one-relationships\">\n<h4>Many-to-one relationships<a class=\"heading-anchor\" href=\"#many-to-one-relationships\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>To define a many-to-one relationship, use <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">django.db.models.ForeignKey</code></a>.\nYou use it just like any other <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> type: by\nincluding it as a class attribute of your model.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a> requires a positional argument: the class\nto which the model is related.</p>\n<p>For example, if a <code class=\"docutils literal notranslate\">Car</code> model has a <code class=\"docutils literal notranslate\">Manufacturer</code> -- that is, a\n<code class=\"docutils literal notranslate\">Manufacturer</code> makes multiple cars but each <code class=\"docutils literal notranslate\">Car</code> only has one\n<code class=\"docutils literal notranslate\">Manufacturer</code> -- use the following definitions:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Manufacturer</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">pass</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Car</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    manufacturer <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>Manufacturer<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">)</span>\n    <span class=\"c1\"># ...</span>\n</code></pre></div>\n<p>You can also create <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#recursive-relationships\"><span class=\"std std-ref\">recursive relationships</span></a> (an\nobject with a many-to-one relationship to itself) and <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#lazy-relationships\"><span class=\"std std-ref\">relationships to\nmodels not yet defined</span></a>; see <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#ref-foreignkey\"><span class=\"std std-ref\">the model field\nreference</span></a> for details.</p>\n<p>It's suggested, but not required, that the name of a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a> field (<code class=\"docutils literal notranslate\">manufacturer</code> in the example\nabove) be the name of the model, lowercase. You can, of course, call the field\nwhatever you want. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Car</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    company_that_makes_it <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>\n        Manufacturer<span class=\"p\">,</span>\n        on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span>\n    <span class=\"p\">)</span>\n    <span class=\"c1\"># ...</span>\n</code></pre></div>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">See also</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a> fields accept a number of extra\narguments which are explained in <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#foreign-key-arguments\"><span class=\"std std-ref\">the model field reference</span></a>. These options help define how the relationship\nshould work; all are optional.</p>\n<p>For details on accessing backwards-related objects, see the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/#backwards-related-objects\"><span class=\"std std-ref\">Following relationships backward example</span></a>.</p>\n<p>For sample code, see the <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/examples/many_to_one/\"><span class=\"doc\">Many-to-one relationship model example</span></a>.</p>\n</aside>\n</section>\n<section id=\"many-to-many-relationships\">\n<h4>Many-to-many relationships<a class=\"heading-anchor\" href=\"#many-to-many-relationships\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>To define a many-to-many relationship, use\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a>. You use it just like any other\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> type: by including it as a class attribute of\nyour model.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> requires a positional argument: the\nclass to which the model is related.</p>\n<p>For example, if a <code class=\"docutils literal notranslate\">Pizza</code> has multiple <code class=\"docutils literal notranslate\">Topping</code> objects -- that is, a\n<code class=\"docutils literal notranslate\">Topping</code> can be on multiple pizzas and each <code class=\"docutils literal notranslate\">Pizza</code> has multiple toppings\n-- here's how you'd represent that:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Topping</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">pass</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Pizza</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    toppings <span class=\"o\">=</span> models<span class=\"o\">.</span>ManyToManyField<span class=\"p\">(</span>Topping<span class=\"p\">)</span>\n</code></pre></div>\n<p>As with <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a>, you can also create\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#recursive-relationships\"><span class=\"std std-ref\">recursive relationships</span></a> (an object with a\nmany-to-many relationship to itself) and <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#lazy-relationships\"><span class=\"std std-ref\">relationships to models not yet\ndefined</span></a>.</p>\n<p>It's suggested, but not required, that the name of a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> (<code class=\"docutils literal notranslate\">toppings</code> in the example above)\nbe a plural describing the set of related model objects.</p>\n<p>It doesn't matter which model has the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a>, but you should only put it in one\nof the models -- not both.</p>\n<p>Generally, <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> instances should go in\nthe object that's going to be edited on a form. In the above example,\n<code class=\"docutils literal notranslate\">toppings</code> is in <code class=\"docutils literal notranslate\">Pizza</code> (rather than <code class=\"docutils literal notranslate\">Topping</code> having a <code class=\"docutils literal notranslate\">pizzas</code>\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> ) because it's more natural to think\nabout a pizza having toppings than a topping being on multiple pizzas. The way\nit's set up above, the <code class=\"docutils literal notranslate\">Pizza</code> form would let users select the toppings.</p>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">See also</p>\n<p>See the <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/examples/many_to_many/\"><span class=\"doc\">Many-to-many relationship model example</span></a> for a full example.</p>\n</aside>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> fields also accept a number of\nextra arguments which are explained in <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#manytomany-arguments\"><span class=\"std std-ref\">the model field reference</span></a>. These options help define how the relationship\nshould work; all are optional.</p>\n</section>\n<section id=\"extra-fields-on-many-to-many-relationships\">\n<span id=\"intermediary-manytomany\"></span><h4>Extra fields on many-to-many relationships<a class=\"heading-anchor\" href=\"#extra-fields-on-many-to-many-relationships\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>When you're only dealing with simple many-to-many relationships such as\nmixing and matching pizzas and toppings, a standard\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> is all you need. However, sometimes\nyou may need to associate data with the relationship between two models.</p>\n<p>For example, consider the case of an application tracking the musical groups\nwhich musicians belong to. There is a many-to-many relationship between a person\nand the groups of which they are a member, so you could use a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> to represent this relationship.\nHowever, there is a lot of detail about the membership that you might want to\ncollect, such as the date at which the person joined the group.</p>\n<p>For these situations, Django allows you to specify the model that will be used\nto govern the many-to-many relationship. You can then put extra fields on the\nintermediate model. The intermediate model is associated with the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> using the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField.through\" title=\"django.db.models.ManyToManyField.through\"><code class=\"xref py py-attr docutils literal notranslate\">through</code></a> argument to point to the model\nthat will act as an intermediary. For our musician example, the code would look\nsomething like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">128</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__str__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span>name\n\n<span class=\"k\">class</span> <span class=\"nc\">Group</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">128</span><span class=\"p\">)</span>\n    members <span class=\"o\">=</span> models<span class=\"o\">.</span>ManyToManyField<span class=\"p\">(</span>Person<span class=\"p\">,</span> through<span class=\"o\">=</span><span class=\"s1\">&#39;Membership&#39;</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__str__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span>name\n\n<span class=\"k\">class</span> <span class=\"nc\">Membership</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    person <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>Person<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">)</span>\n    group <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>Group<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">)</span>\n    date_joined <span class=\"o\">=</span> models<span class=\"o\">.</span>DateField<span class=\"p\">()</span>\n    invite_reason <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">64</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>When you set up the intermediary model, you explicitly specify foreign\nkeys to the models that are involved in the many-to-many relationship. This\nexplicit declaration defines how the two models are related.</p>\n<p>There are a few restrictions on the intermediate model:</p>\n<ul class=\"simple\">\n<li><p>Your intermediate model must contain one - and <em>only</em> one - foreign key\nto the source model (this would be <code class=\"docutils literal notranslate\">Group</code> in our example), or you must\nexplicitly specify the foreign keys Django should use for the relationship\nusing <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField.through_fields\" title=\"django.db.models.ManyToManyField.through_fields\"><code class=\"xref py py-attr docutils literal notranslate\">ManyToManyField.through_fields</code></a>.\nIf you have more than one foreign key and <code class=\"docutils literal notranslate\">through_fields</code> is not\nspecified, a validation error will be raised. A similar restriction applies\nto the foreign key to the target model (this would be <code class=\"docutils literal notranslate\">Person</code> in our\nexample).</p></li>\n<li><p>For a model which has a many-to-many relationship to itself through an\nintermediary model, two foreign keys to the same model are permitted, but\nthey will be treated as the two (different) sides of the many-to-many\nrelationship. If there are <em>more</em> than two foreign keys though, you\nmust also specify <code class=\"docutils literal notranslate\">through_fields</code> as above, or a validation error\nwill be raised.</p></li>\n<li><p>When defining a many-to-many relationship from a model to\nitself, using an intermediary model, you <em>must</em> use\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField.symmetrical\" title=\"django.db.models.ManyToManyField.symmetrical\"><code class=\"xref py py-attr docutils literal notranslate\">symmetrical=False</code></a> (see\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#manytomany-arguments\"><span class=\"std std-ref\">the model field reference</span></a>).</p></li>\n</ul>\n<p>Now that you have set up your <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> to use\nyour intermediary model (<code class=\"docutils literal notranslate\">Membership</code>, in this case), you're ready to start\ncreating some many-to-many relationships. You do this by creating instances of\nthe intermediate model:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>ringo <span class=\"o\">=</span> Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Ringo Starr&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>paul <span class=\"o\">=</span> Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Paul McCartney&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles <span class=\"o\">=</span> Group<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;The Beatles&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>m1 <span class=\"o\">=</span> Membership<span class=\"p\">(</span>person<span class=\"o\">=</span>ringo<span class=\"p\">,</span> group<span class=\"o\">=</span>beatles<span class=\"p\">,</span>\n<span class=\"gp\">... </span>    date_joined<span class=\"o\">=</span>date<span class=\"p\">(</span><span class=\"mi\">1962</span><span class=\"p\">,</span> <span class=\"mi\">8</span><span class=\"p\">,</span> <span class=\"mi\">16</span><span class=\"p\">),</span>\n<span class=\"gp\">... </span>    invite_reason<span class=\"o\">=</span><span class=\"s2\">&quot;Needed a new drummer.&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>m1<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Person: Ringo Starr&gt;]&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>ringo<span class=\"o\">.</span>group_set<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Group: The Beatles&gt;]&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>m2 <span class=\"o\">=</span> Membership<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>person<span class=\"o\">=</span>paul<span class=\"p\">,</span> group<span class=\"o\">=</span>beatles<span class=\"p\">,</span>\n<span class=\"gp\">... </span>    date_joined<span class=\"o\">=</span>date<span class=\"p\">(</span><span class=\"mi\">1960</span><span class=\"p\">,</span> <span class=\"mi\">8</span><span class=\"p\">,</span> <span class=\"mi\">1</span><span class=\"p\">),</span>\n<span class=\"gp\">... </span>    invite_reason<span class=\"o\">=</span><span class=\"s2\">&quot;Wanted to form a band.&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Person: Ringo Starr&gt;, &lt;Person: Paul McCartney&gt;]&gt;</span>\n</code></pre></div>\n<p>Unlike normal many-to-many fields, you <em>can't</em> use <code class=\"docutils literal notranslate\">add()</code>, <code class=\"docutils literal notranslate\">create()</code>,\nor <code class=\"docutils literal notranslate\">set()</code> to create relationships:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># The following statements will not work</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>add<span class=\"p\">(</span>john<span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>create<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;George Harrison&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>set<span class=\"p\">([</span>john<span class=\"p\">,</span> paul<span class=\"p\">,</span> ringo<span class=\"p\">,</span> george<span class=\"p\">])</span>\n</code></pre></div>\n<p>Why? You can't just create a relationship between a <code class=\"docutils literal notranslate\">Person</code> and a <code class=\"docutils literal notranslate\">Group</code>\n- you need to specify all the detail for the relationship required by the\n<code class=\"docutils literal notranslate\">Membership</code> model. The simple <code class=\"docutils literal notranslate\">add</code>, <code class=\"docutils literal notranslate\">create</code> and assignment calls\ndon't provide a way to specify this extra detail. As a result, they are\ndisabled for many-to-many relationships that use an intermediate model.\nThe only way to create this type of relationship is to create instances of the\nintermediate model.</p>\n<p>The <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove\" title=\"django.db.models.fields.related.RelatedManager.remove\"><code class=\"xref py py-meth docutils literal notranslate\">remove()</code></a> method is\ndisabled for similar reasons. For example, if the custom through table defined\nby the intermediate model does not enforce uniqueness on the\n<code class=\"docutils literal notranslate\">(model1, model2)</code> pair, a <code class=\"docutils literal notranslate\">remove()</code> call would not provide enough\ninformation as to which intermediate model instance should be deleted:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>Membership<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>person<span class=\"o\">=</span>ringo<span class=\"p\">,</span> group<span class=\"o\">=</span>beatles<span class=\"p\">,</span>\n<span class=\"gp\">... </span>    date_joined<span class=\"o\">=</span>date<span class=\"p\">(</span><span class=\"mi\">1968</span><span class=\"p\">,</span> <span class=\"mi\">9</span><span class=\"p\">,</span> <span class=\"mi\">4</span><span class=\"p\">),</span>\n<span class=\"gp\">... </span>    invite_reason<span class=\"o\">=</span><span class=\"s2\">&quot;You&#39;ve been gone for a month and we miss you.&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Person: Ringo Starr&gt;, &lt;Person: Paul McCartney&gt;, &lt;Person: Ringo Starr&gt;]&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># This will not work because it cannot tell which membership to remove</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>remove<span class=\"p\">(</span>ringo<span class=\"p\">)</span>\n</code></pre></div>\n<p>However, the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear\" title=\"django.db.models.fields.related.RelatedManager.clear\"><code class=\"xref py py-meth docutils literal notranslate\">clear()</code></a>\nmethod can be used to remove all many-to-many relationships for an instance:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># Beatles have broken up</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>beatles<span class=\"o\">.</span>members<span class=\"o\">.</span>clear<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># Note that this deletes the intermediate model instances</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Membership<span class=\"o\">.</span>objects<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet []&gt;</span>\n</code></pre></div>\n<p>Once you have established the many-to-many relationships by creating instances\nof your intermediate model, you can issue queries. Just as with normal\nmany-to-many relationships, you can query using the attributes of the\nmany-to-many-related model:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Find all the groups with a member whose name starts with &#39;Paul&#39;</span>\n<span class=\"o\">&gt;&gt;&gt;</span> Group<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>members__name__startswith<span class=\"o\">=</span><span class=\"s1\">&#39;Paul&#39;</span><span class=\"p\">)</span>\n<span class=\"o\">&lt;</span>QuerySet <span class=\"p\">[</span><span class=\"o\">&lt;</span>Group<span class=\"p\">:</span> The Beatles<span class=\"o\">&gt;</span><span class=\"p\">]</span><span class=\"o\">&gt;</span>\n</code></pre></div>\n<p>As you are using an intermediate model, you can also query on its attributes:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Find all the members of the Beatles that joined after 1 Jan 1961</span>\n<span class=\"o\">&gt;&gt;&gt;</span> Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>\n<span class=\"o\">...</span>     group__name<span class=\"o\">=</span><span class=\"s1\">&#39;The Beatles&#39;</span><span class=\"p\">,</span>\n<span class=\"o\">...</span>     membership__date_joined__gt<span class=\"o\">=</span>date<span class=\"p\">(</span><span class=\"mi\">1961</span><span class=\"p\">,</span><span class=\"mi\">1</span><span class=\"p\">,</span><span class=\"mi\">1</span><span class=\"p\">))</span>\n<span class=\"o\">&lt;</span>QuerySet <span class=\"p\">[</span><span class=\"o\">&lt;</span>Person<span class=\"p\">:</span> Ringo Starr<span class=\"p\">]</span><span class=\"o\">&gt;</span>\n</code></pre></div>\n<p>If you need to access a membership's information you may do so by directly\nquerying the <code class=\"docutils literal notranslate\">Membership</code> model:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership <span class=\"o\">=</span> Membership<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>group<span class=\"o\">=</span>beatles<span class=\"p\">,</span> person<span class=\"o\">=</span>ringo<span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership<span class=\"o\">.</span>date_joined\n<span class=\"go\">datetime.date(1962, 8, 16)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership<span class=\"o\">.</span>invite_reason\n<span class=\"go\">&#39;Needed a new drummer.&#39;</span>\n</code></pre></div>\n<p>Another way to access the same information is by querying the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/#m2m-reverse-relationships\"><span class=\"std std-ref\">many-to-many reverse relationship</span></a> from a\n<code class=\"docutils literal notranslate\">Person</code> object:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership <span class=\"o\">=</span> ringo<span class=\"o\">.</span>membership_set<span class=\"o\">.</span>get<span class=\"p\">(</span>group<span class=\"o\">=</span>beatles<span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership<span class=\"o\">.</span>date_joined\n<span class=\"go\">datetime.date(1962, 8, 16)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>ringos_membership<span class=\"o\">.</span>invite_reason\n<span class=\"go\">&#39;Needed a new drummer.&#39;</span>\n</code></pre></div>\n</section>\n<section id=\"one-to-one-relationships\">\n<h4>One-to-one relationships<a class=\"heading-anchor\" href=\"#one-to-one-relationships\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>To define a one-to-one relationship, use\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a>. You use it just like any other\n<code class=\"docutils literal notranslate\">Field</code> type: by including it as a class attribute of your model.</p>\n<p>This is most useful on the primary key of an object when that object &quot;extends&quot;\nanother object in some way.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> requires a positional argument: the\nclass to which the model is related.</p>\n<p>For example, if you were building a database of &quot;places&quot;, you would\nbuild pretty standard stuff such as address, phone number, etc. in the\ndatabase. Then, if you wanted to build a database of restaurants on\ntop of the places, instead of repeating yourself and replicating those\nfields in the <code class=\"docutils literal notranslate\">Restaurant</code> model, you could make <code class=\"docutils literal notranslate\">Restaurant</code> have\na <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> to <code class=\"docutils literal notranslate\">Place</code> (because a\nrestaurant &quot;is a&quot; place; in fact, to handle this you'd typically use\n<a class=\"reference internal\" href=\"#model-inheritance\"><span class=\"std std-ref\">inheritance</span></a>, which involves an implicit\none-to-one relation).</p>\n<p>As with <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a>, a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#recursive-relationships\"><span class=\"std std-ref\">recursive relationship</span></a> can be defined and <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#lazy-relationships\"><span class=\"std std-ref\">references to as-yet\nundefined models</span></a> can be made.</p>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">See also</p>\n<p>See the <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/examples/one_to_one/\"><span class=\"doc\">One-to-one relationship model example</span></a> for a full example.</p>\n</aside>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> fields also accept an optional\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField.parent_link\" title=\"django.db.models.OneToOneField.parent_link\"><code class=\"xref py py-attr docutils literal notranslate\">parent_link</code></a> argument.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> classes used to automatically become\nthe primary key on a model. This is no longer true (although you can manually\npass in the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.primary_key\" title=\"django.db.models.Field.primary_key\"><code class=\"xref py py-attr docutils literal notranslate\">primary_key</code></a> argument if you like).\nThus, it's now possible to have multiple fields of type\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> on a single model.</p>\n</section>\n</section>\n<section id=\"models-across-files\">\n<h3>Models across files<a class=\"heading-anchor\" href=\"#models-across-files\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>It's perfectly OK to relate a model to one from another app. To do this, import\nthe related model at the top of the file where your model is defined. Then,\njust refer to the other model class wherever needed. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n<span class=\"kn\">from</span> <span class=\"nn\">geography.models</span> <span class=\"kn\">import</span> ZipCode\n\n<span class=\"k\">class</span> <span class=\"nc\">Restaurant</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    zip_code <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>\n        ZipCode<span class=\"p\">,</span>\n        on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>SET_NULL<span class=\"p\">,</span>\n        blank<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">,</span>\n        null<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">,</span>\n    <span class=\"p\">)</span>\n</code></pre></div>\n</section>\n<section id=\"field-name-restrictions\">\n<h3>Field name restrictions<a class=\"heading-anchor\" href=\"#field-name-restrictions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django places only two restrictions on model field names:</p>\n<ol class=\"arabic\">\n<li><p>A field name cannot be a Python reserved word, because that would result\nin a Python syntax error. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Example</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"k\">pass</span> <span class=\"o\">=</span> models<span class=\"o\">.</span>IntegerField<span class=\"p\">()</span> <span class=\"c1\"># &#39;pass&#39; is a reserved word!</span>\n</code></pre></div>\n</li>\n<li><p>A field name cannot contain more than one underscore in a row, due to\nthe way Django's query lookup syntax works. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Example</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    foo__bar <span class=\"o\">=</span> models<span class=\"o\">.</span>IntegerField<span class=\"p\">()</span> <span class=\"c1\"># &#39;foo__bar&#39; has two underscores!</span>\n</code></pre></div>\n</li>\n</ol>\n<p>These limitations can be worked around, though, because your field name doesn't\nnecessarily have to match your database column name. See the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field.db_column\" title=\"django.db.models.Field.db_column\"><code class=\"xref py py-attr docutils literal notranslate\">db_column</code></a> option.</p>\n<p>SQL reserved words, such as <code class=\"docutils literal notranslate\">join</code>, <code class=\"docutils literal notranslate\">where</code> or <code class=\"docutils literal notranslate\">select</code>, <em>are</em> allowed as\nmodel field names, because Django escapes all database table names and column\nnames in every underlying SQL query. It uses the quoting syntax of your\nparticular database engine.</p>\n</section>\n<section id=\"custom-field-types\">\n<h3>Custom field types<a class=\"heading-anchor\" href=\"#custom-field-types\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If one of the existing model fields cannot be used to fit your purposes, or if\nyou wish to take advantage of some less common database column types, you can\ncreate your own field class. Full coverage of creating your own fields is\nprovided in <a class=\"reference internal\" href=\"/zh-hans/2.0/howto/custom-model-fields/\"><span class=\"doc\">编写自定义 model fields</span></a>.</p>\n</section>\n</section>\n<section id=\"meta-options\">\n<span id=\"id3\"></span><h2><code class=\"docutils literal notranslate\">Meta</code> options<a class=\"heading-anchor\" href=\"#meta-options\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Give your model metadata by using an inner <code class=\"docutils literal notranslate\">class Meta</code>, like so:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Ox</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    horn_length <span class=\"o\">=</span> models<span class=\"o\">.</span>IntegerField<span class=\"p\">()</span>\n\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        ordering <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"s2\">&quot;horn_length&quot;</span><span class=\"p\">]</span>\n        verbose_name_plural <span class=\"o\">=</span> <span class=\"s2\">&quot;oxen&quot;</span>\n</code></pre></div>\n<p>Model metadata is &quot;anything that's not a field&quot;, such as ordering options\n(<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.ordering\" title=\"django.db.models.Options.ordering\"><code class=\"xref py py-attr docutils literal notranslate\">ordering</code></a>), database table name (<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.db_table\" title=\"django.db.models.Options.db_table\"><code class=\"xref py py-attr docutils literal notranslate\">db_table</code></a>), or\nhuman-readable singular and plural names (<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.verbose_name\" title=\"django.db.models.Options.verbose_name\"><code class=\"xref py py-attr docutils literal notranslate\">verbose_name</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.verbose_name_plural\" title=\"django.db.models.Options.verbose_name_plural\"><code class=\"xref py py-attr docutils literal notranslate\">verbose_name_plural</code></a>). None are required, and adding <code class=\"docutils literal notranslate\">class\nMeta</code> to a model is completely optional.</p>\n<p>A complete list of all possible <code class=\"docutils literal notranslate\">Meta</code> options can be found in the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/\"><span class=\"doc\">model\noption reference</span></a>.</p>\n</section>\n<section id=\"model-attributes\">\n<span id=\"id4\"></span><h2>Model attributes<a class=\"heading-anchor\" href=\"#model-attributes\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\">objects</code></dt><dd><p>The most important attribute of a model is the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/managers/#django.db.models.Manager\" title=\"django.db.models.Manager\"><code class=\"xref py py-class docutils literal notranslate\">Manager</code></a>. It's the interface through which\ndatabase query operations are provided to Django models and is used to\n<a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/#retrieving-objects\"><span class=\"std std-ref\">retrieve the instances</span></a> from the database. If no\ncustom <code class=\"docutils literal notranslate\">Manager</code> is defined, the default name is\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/class/#django.db.models.Model.objects\" title=\"django.db.models.Model.objects\"><code class=\"xref py py-attr docutils literal notranslate\">objects</code></a>. Managers are only accessible via\nmodel classes, not the model instances.</p>\n</dd>\n</dl>\n</section>\n<section id=\"model-methods\">\n<span id=\"id5\"></span><h2>Model methods<a class=\"heading-anchor\" href=\"#model-methods\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Define custom methods on a model to add custom &quot;row-level&quot; functionality to your\nobjects. Whereas <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/managers/#django.db.models.Manager\" title=\"django.db.models.Manager\"><code class=\"xref py py-class docutils literal notranslate\">Manager</code></a> methods are intended to do\n&quot;table-wide&quot; things, model methods should act on a particular model instance.</p>\n<p>This is a valuable technique for keeping business logic in one place -- the\nmodel.</p>\n<p>For example, this model has a few custom methods:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    last_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    birth_date <span class=\"o\">=</span> models<span class=\"o\">.</span>DateField<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">baby_boomer_status</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"s2\">&quot;Returns the person&#39;s baby-boomer status.&quot;</span>\n        <span class=\"kn\">import</span> <span class=\"nn\">datetime</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>birth_date <span class=\"o\">&lt;</span> datetime<span class=\"o\">.</span>date<span class=\"p\">(</span><span class=\"mi\">1945</span><span class=\"p\">,</span> <span class=\"mi\">8</span><span class=\"p\">,</span> <span class=\"mi\">1</span><span class=\"p\">):</span>\n            <span class=\"k\">return</span> <span class=\"s2\">&quot;Pre-boomer&quot;</span>\n        <span class=\"k\">elif</span> <span class=\"bp\">self</span><span class=\"o\">.</span>birth_date <span class=\"o\">&lt;</span> datetime<span class=\"o\">.</span>date<span class=\"p\">(</span><span class=\"mi\">1965</span><span class=\"p\">,</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"mi\">1</span><span class=\"p\">):</span>\n            <span class=\"k\">return</span> <span class=\"s2\">&quot;Baby boomer&quot;</span>\n        <span class=\"k\">else</span><span class=\"p\">:</span>\n            <span class=\"k\">return</span> <span class=\"s2\">&quot;Post-boomer&quot;</span>\n\n    <span class=\"nd\">@property</span>\n    <span class=\"k\">def</span> <span class=\"nf\">full_name</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"s2\">&quot;Returns the person&#39;s full name.&quot;</span>\n        <span class=\"k\">return</span> <span class=\"s1\">&#39;</span><span class=\"si\">%s</span><span class=\"s1\"> </span><span class=\"si\">%s</span><span class=\"s1\">&#39;</span> <span class=\"o\">%</span> <span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span>first_name<span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"o\">.</span>last_name<span class=\"p\">)</span>\n</code></pre></div>\n<p>The last method in this example is a <a class=\"reference internal\" href=\"/zh-hans/2.0/glossary/#term-property\"><span class=\"xref std std-term\">property</span></a>.</p>\n<p>The <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/\"><span class=\"doc\">model instance reference</span></a> has a complete list\nof <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#model-instance-methods\"><span class=\"std std-ref\">methods automatically given to each model</span></a>.\nYou can override most of these -- see <a class=\"reference internal\" href=\"#overriding-predefined-model-methods\">overriding predefined model methods</a>,\nbelow -- but there are a couple that you'll almost always want to define:</p>\n<dl>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.__str__\" title=\"django.db.models.Model.__str__\"><code class=\"xref py py-meth docutils literal notranslate\">__str__()</code></a></dt><dd><p>A Python &quot;magic method&quot; that returns a string representation of any\nobject. This is what Python and Django will use whenever a model\ninstance needs to be coerced and displayed as a plain string. Most\nnotably, this happens when you display an object in an interactive\nconsole or in the admin.</p>\n<p>You'll always want to define this method; the default isn't very helpful\nat all.</p>\n</dd>\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.get_absolute_url\" title=\"django.db.models.Model.get_absolute_url\"><code class=\"xref py py-meth docutils literal notranslate\">get_absolute_url()</code></a></dt><dd><p>This tells Django how to calculate the URL for an object. Django uses\nthis in its admin interface, and any time it needs to figure out a URL\nfor an object.</p>\n<p>Any object that has a URL that uniquely identifies it should define this\nmethod.</p>\n</dd>\n</dl>\n<section id=\"overriding-predefined-model-methods\">\n<span id=\"overriding-model-methods\"></span><h3>Overriding predefined model methods<a class=\"heading-anchor\" href=\"#overriding-predefined-model-methods\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>There's another set of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#model-instance-methods\"><span class=\"std std-ref\">model methods</span></a> that\nencapsulate a bunch of database behavior that you'll want to customize. In\nparticular you'll often want to change the way <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.delete\" title=\"django.db.models.Model.delete\"><code class=\"xref py py-meth docutils literal notranslate\">delete()</code></a> work.</p>\n<p>You're free to override these methods (and any other model method) to alter\nbehavior.</p>\n<p>A classic use-case for overriding the built-in methods is if you want something\nto happen whenever you save an object. For example (see\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> for documentation of the parameters it accepts):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Blog</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n    tagline <span class=\"o\">=</span> models<span class=\"o\">.</span>TextField<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">save</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"o\">*</span>args<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">):</span>\n        do_something<span class=\"p\">()</span>\n        <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span>save<span class=\"p\">(</span><span class=\"o\">*</span>args<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">)</span>  <span class=\"c1\"># Call the &quot;real&quot; save() method.</span>\n        do_something_else<span class=\"p\">()</span>\n</code></pre></div>\n<p>You can also prevent saving:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Blog</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n    tagline <span class=\"o\">=</span> models<span class=\"o\">.</span>TextField<span class=\"p\">()</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">save</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"o\">*</span>args<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">):</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>name <span class=\"o\">==</span> <span class=\"s2\">&quot;Yoko Ono&#39;s blog&quot;</span><span class=\"p\">:</span>\n            <span class=\"k\">return</span> <span class=\"c1\"># Yoko shall never have her own blog!</span>\n        <span class=\"k\">else</span><span class=\"p\">:</span>\n            <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span>save<span class=\"p\">(</span><span class=\"o\">*</span>args<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">)</span>  <span class=\"c1\"># Call the &quot;real&quot; save() method.</span>\n</code></pre></div>\n<p>It's important to remember to call the superclass method -- that's\nthat <code class=\"docutils literal notranslate\">super().save(*args, **kwargs)</code> business -- to ensure\nthat the object still gets saved into the database. If you forget to\ncall the superclass method, the default behavior won't happen and the\ndatabase won't get touched.</p>\n<p>It's also important that you pass through the arguments that can be\npassed to the model method -- that's what the <code class=\"docutils literal notranslate\">*args, **kwargs</code> bit\ndoes. Django will, from time to time, extend the capabilities of\nbuilt-in model methods, adding new arguments. If you use <code class=\"docutils literal notranslate\">*args,\n**kwargs</code> in your method definitions, you are guaranteed that your\ncode will automatically support those arguments when they are added.</p>\n<aside class=\"admonition-overridden-model-methods-are-not-called-on-bulk-operations admonition\" role=\"note\">\n<p class=\"admonition-title\">Overridden model methods are not called on bulk operations</p>\n<p>Note that the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.delete\" title=\"django.db.models.Model.delete\"><code class=\"xref py py-meth docutils literal notranslate\">delete()</code></a> method for an object is not\nnecessarily called when <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/#topics-db-queries-delete\"><span class=\"std std-ref\">deleting objects in bulk using a\nQuerySet</span></a> or as a result of a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.on_delete\" title=\"django.db.models.ForeignKey.on_delete\"><code class=\"xref py py-attr docutils literal notranslate\">cascading\ndelete</code></a>. To ensure customized\ndelete logic gets executed, you can use\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/signals/#django.db.models.signals.pre_delete\" title=\"django.db.models.signals.pre_delete\"><code class=\"xref py py-data docutils literal notranslate\">pre_delete</code></a> and/or\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/signals/#django.db.models.signals.post_delete\" title=\"django.db.models.signals.post_delete\"><code class=\"xref py py-data docutils literal notranslate\">post_delete</code></a> signals.</p>\n<p>Unfortunately, there isn't a workaround when\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create\" title=\"django.db.models.query.QuerySet.bulk_create\"><code class=\"xref py py-meth docutils literal notranslate\">creating</code></a> or\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/querysets/#django.db.models.query.QuerySet.update\" title=\"django.db.models.query.QuerySet.update\"><code class=\"xref py py-meth docutils literal notranslate\">updating</code></a> objects in bulk,\nsince none of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a>,\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/signals/#django.db.models.signals.pre_save\" title=\"django.db.models.signals.pre_save\"><code class=\"xref py py-data docutils literal notranslate\">pre_save</code></a>, and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/signals/#django.db.models.signals.post_save\" title=\"django.db.models.signals.post_save\"><code class=\"xref py py-data docutils literal notranslate\">post_save</code></a> are called.</p>\n</aside>\n</section>\n<section id=\"executing-custom-sql\">\n<h3>Executing custom SQL<a class=\"heading-anchor\" href=\"#executing-custom-sql\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Another common pattern is writing custom SQL statements in model methods and\nmodule-level methods. For more details on using raw SQL, see the documentation\non <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/sql/\"><span class=\"doc\">using raw SQL</span></a>.</p>\n</section>\n</section>\n<section id=\"model-inheritance\">\n<span id=\"id6\"></span><h2>模型继承<a class=\"heading-anchor\" href=\"#model-inheritance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>模型继承在 Django 中与普通类继承在 Python 中的工作方式几乎完全相同, 但也仍应遵循本页开头的内容. 这意味着其基类应该继承自 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/instances/#django.db.models.Model\" title=\"django.db.models.Model\"><code class=\"xref py py-class docutils literal notranslate\">django.db.models.Model</code></a> .</p>\n<p>The only decision you have to make is whether you want the parent models to be\nmodels in their own right (with their own database tables), or if the parents\nare just holders of common information that will only be visible through the\nchild models.</p>\n<p>There are three styles of inheritance that are possible in Django.</p>\n<ol class=\"arabic simple\">\n<li><p>Often, you will just want to use the parent class to hold information that\nyou don't want to have to type out for each child model. This class isn't\ngoing to ever be used in isolation, so <a class=\"reference internal\" href=\"#abstract-base-classes\"><span class=\"std std-ref\">Abstract base classes</span></a> are\nwhat you're after.</p></li>\n<li><p>If you're subclassing an existing model (perhaps something from another\napplication entirely) and want each model to have its own database table,\n<a class=\"reference internal\" href=\"#multi-table-inheritance\"><span class=\"std std-ref\">Multi-table inheritance</span></a> is the way to go.</p></li>\n<li><p>Finally, if you only want to modify the Python-level behavior of a model,\nwithout changing the models fields in any way, you can use\n<a class=\"reference internal\" href=\"#proxy-models\"><span class=\"std std-ref\">Proxy models</span></a>.</p></li>\n</ol>\n<section id=\"abstract-base-classes\">\n<span id=\"id7\"></span><h3>Abstract base classes<a class=\"heading-anchor\" href=\"#abstract-base-classes\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Abstract base classes are useful when you want to put some common\ninformation into a number of other models. You write your base class\nand put <code class=\"docutils literal notranslate\">abstract=True</code> in the <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>\nclass. This model will then not be used to create any database\ntable. Instead, when it is used as a base class for other models, its\nfields will be added to those of the child class.</p>\n<p>An example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">CommonInfo</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n    age <span class=\"o\">=</span> models<span class=\"o\">.</span>PositiveIntegerField<span class=\"p\">()</span>\n\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        abstract <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Student</span><span class=\"p\">(</span>CommonInfo<span class=\"p\">):</span>\n    home_group <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">5</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>The <code class=\"docutils literal notranslate\">Student</code> model will have three fields: <code class=\"docutils literal notranslate\">name</code>, <code class=\"docutils literal notranslate\">age</code> and\n<code class=\"docutils literal notranslate\">home_group</code>. The <code class=\"docutils literal notranslate\">CommonInfo</code> model cannot be used as a normal Django\nmodel, since it is an abstract base class. It does not generate a database\ntable or have a manager, and cannot be instantiated or saved directly.</p>\n<p>Fields inherited from abstract base classes can be overridden with another\nfield or value, or be removed with <code class=\"docutils literal notranslate\">None</code>.</p>\n<p>For many uses, this type of model inheritance will be exactly what you want.\nIt provides a way to factor out common information at the Python level, while\nstill only creating one database table per child model at the database level.</p>\n<section id=\"meta-inheritance\">\n<h4><code class=\"docutils literal notranslate\">Meta</code> inheritance<a class=\"heading-anchor\" href=\"#meta-inheritance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>When an abstract base class is created, Django makes any <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>\ninner class you declared in the base class available as an\nattribute. If a child class does not declare its own <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>\nclass, it will inherit the parent's <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>. If the child wants to\nextend the parent's <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class, it can subclass it. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">CommonInfo</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        abstract <span class=\"o\">=</span> <span class=\"kc\">True</span>\n        ordering <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"s1\">&#39;name&#39;</span><span class=\"p\">]</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Student</span><span class=\"p\">(</span>CommonInfo<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">(</span>CommonInfo<span class=\"o\">.</span>Meta<span class=\"p\">):</span>\n        db_table <span class=\"o\">=</span> <span class=\"s1\">&#39;student_info&#39;</span>\n</code></pre></div>\n<p>Django does make one adjustment to the <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class of an abstract base\nclass: before installing the <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> attribute, it sets <code class=\"docutils literal notranslate\">abstract=False</code>.\nThis means that children of abstract base classes don't automatically become\nabstract classes themselves. Of course, you can make an abstract base class\nthat inherits from another abstract base class. You just need to remember to\nexplicitly set <code class=\"docutils literal notranslate\">abstract=True</code> each time.</p>\n<p>Some attributes won't make sense to include in the <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class of an\nabstract base class. For example, including <code class=\"docutils literal notranslate\">db_table</code> would mean that all\nthe child classes (the ones that don't specify their own <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>) would use\nthe same database table, which is almost certainly not what you want.</p>\n</section>\n<section id=\"be-careful-with-related-name-and-related-query-name\">\n<span id=\"abstract-related-name\"></span><h4>Be careful with <code class=\"docutils literal notranslate\">related_name</code> and <code class=\"docutils literal notranslate\">related_query_name</code><a class=\"heading-anchor\" href=\"#be-careful-with-related-name-and-related-query-name\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If you are using <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a> or\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_query_name\" title=\"django.db.models.ForeignKey.related_query_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_query_name</code></a> on a <code class=\"docutils literal notranslate\">ForeignKey</code> or\n<code class=\"docutils literal notranslate\">ManyToManyField</code>, you must always specify a <em>unique</em> reverse name and query\nname for the field. This would normally cause a problem in abstract base\nclasses, since the fields on this class are included into each of the child\nclasses, with exactly the same values for the attributes (including\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_query_name\" title=\"django.db.models.ForeignKey.related_query_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_query_name</code></a>) each time.</p>\n<p>To work around this problem, when you are using\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a> or\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_query_name\" title=\"django.db.models.ForeignKey.related_query_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_query_name</code></a> in an abstract base\nclass (only), part of the value should contain <code class=\"docutils literal notranslate\">'%(app_label)s'</code> and\n<code class=\"docutils literal notranslate\">'%(class)s'</code>.</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">'%(class)s'</code> is replaced by the lower-cased name of the child class\nthat the field is used in.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'%(app_label)s'</code> is replaced by the lower-cased name of the app the child\nclass is contained within. Each installed application name must be unique\nand the model class names within each app must also be unique, therefore the\nresulting name will end up being different.</p></li>\n</ul>\n<p>For example, given an app <code class=\"docutils literal notranslate\">common/models.py</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Base</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    m2m <span class=\"o\">=</span> models<span class=\"o\">.</span>ManyToManyField<span class=\"p\">(</span>\n        OtherModel<span class=\"p\">,</span>\n        related_name<span class=\"o\">=</span><span class=\"s2\">&quot;</span><span class=\"si\">%(app_label)s</span><span class=\"s2\">_</span><span class=\"si\">%(class)s</span><span class=\"s2\">_related&quot;</span><span class=\"p\">,</span>\n        related_query_name<span class=\"o\">=</span><span class=\"s2\">&quot;</span><span class=\"si\">%(app_label)s</span><span class=\"s2\">_</span><span class=\"si\">%(class)s</span><span class=\"s2\">s&quot;</span><span class=\"p\">,</span>\n    <span class=\"p\">)</span>\n\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        abstract <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">ChildA</span><span class=\"p\">(</span>Base<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">ChildB</span><span class=\"p\">(</span>Base<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n</code></pre></div>\n<p>Along with another app <code class=\"docutils literal notranslate\">rare/models.py</code>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">common.models</span> <span class=\"kn\">import</span> Base\n\n<span class=\"k\">class</span> <span class=\"nc\">ChildB</span><span class=\"p\">(</span>Base<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n</code></pre></div>\n<p>The reverse name of the <code class=\"docutils literal notranslate\">common.ChildA.m2m</code> field will be\n<code class=\"docutils literal notranslate\">common_childa_related</code> and the reverse query name will be <code class=\"docutils literal notranslate\">common_childas</code>.\nThe reverse name of the <code class=\"docutils literal notranslate\">common.ChildB.m2m</code> field will be\n<code class=\"docutils literal notranslate\">common_childb_related</code> and the reverse query name will be\n<code class=\"docutils literal notranslate\">common_childbs</code>. Finally, the reverse name of the <code class=\"docutils literal notranslate\">rare.ChildB.m2m</code> field\nwill be <code class=\"docutils literal notranslate\">rare_childb_related</code> and the reverse query name will be\n<code class=\"docutils literal notranslate\">rare_childbs</code>. It's up to you how you use the <code class=\"docutils literal notranslate\">'%(class)s'</code> and\n<code class=\"docutils literal notranslate\">'%(app_label)s'</code> portion to construct your related name or related query name\nbut if you forget to use it, Django will raise errors when you perform system\nchecks (or run <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a>).</p>\n<p>If you don't specify a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a>\nattribute for a field in an abstract base class, the default reverse name will\nbe the name of the child class followed by <code class=\"docutils literal notranslate\">'_set'</code>, just as it normally\nwould be if you'd declared the field directly on the child class. For example,\nin the above code, if the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a>\nattribute was omitted, the reverse name for the <code class=\"docutils literal notranslate\">m2m</code> field would be\n<code class=\"docutils literal notranslate\">childa_set</code> in the <code class=\"docutils literal notranslate\">ChildA</code> case and <code class=\"docutils literal notranslate\">childb_set</code> for the <code class=\"docutils literal notranslate\">ChildB</code>\nfield.</p>\n</section>\n</section>\n<section id=\"multi-table-inheritance\">\n<span id=\"id8\"></span><h3>Multi-table inheritance<a class=\"heading-anchor\" href=\"#multi-table-inheritance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The second type of model inheritance supported by Django is when each model in\nthe hierarchy is a model all by itself. Each model corresponds to its own\ndatabase table and can be queried and created individually. The inheritance\nrelationship introduces links between the child model and each of its parents\n(via an automatically-created <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a>).\nFor example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Place</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    address <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">80</span><span class=\"p\">)</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Restaurant</span><span class=\"p\">(</span>Place<span class=\"p\">):</span>\n    serves_hot_dogs <span class=\"o\">=</span> models<span class=\"o\">.</span>BooleanField<span class=\"p\">(</span>default<span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n    serves_pizza <span class=\"o\">=</span> models<span class=\"o\">.</span>BooleanField<span class=\"p\">(</span>default<span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>All of the fields of <code class=\"docutils literal notranslate\">Place</code> will also be available in <code class=\"docutils literal notranslate\">Restaurant</code>,\nalthough the data will reside in a different database table. So these are both\npossible:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>Place<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Bob&#39;s Cafe&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Restaurant<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Bob&#39;s Cafe&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>If you have a <code class=\"docutils literal notranslate\">Place</code> that is also a <code class=\"docutils literal notranslate\">Restaurant</code>, you can get from the\n<code class=\"docutils literal notranslate\">Place</code> object to the <code class=\"docutils literal notranslate\">Restaurant</code> object by using the lower-case version\nof the model name:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>p <span class=\"o\">=</span> Place<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">12</span><span class=\"p\">)</span>\n<span class=\"go\"># If p is a Restaurant object, this will give the child class:</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>restaurant\n<span class=\"go\">&lt;Restaurant: ...&gt;</span>\n</code></pre></div>\n<p>However, if <code class=\"docutils literal notranslate\">p</code> in the above example was <em>not</em> a <code class=\"docutils literal notranslate\">Restaurant</code> (it had been\ncreated directly as a <code class=\"docutils literal notranslate\">Place</code> object or was the parent of some other class),\nreferring to <code class=\"docutils literal notranslate\">p.restaurant</code> would raise a <code class=\"docutils literal notranslate\">Restaurant.DoesNotExist</code>\nexception.</p>\n<p>The automatically-created <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> on\n<code class=\"docutils literal notranslate\">Restaurant</code> that links it to <code class=\"docutils literal notranslate\">Place</code> looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>place_ptr <span class=\"o\">=</span> models<span class=\"o\">.</span>OneToOneField<span class=\"p\">(</span>\n    Place<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span>\n    parent_link<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">,</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>You can override that field by declaring your own\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> with <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField.parent_link\" title=\"django.db.models.OneToOneField.parent_link\"><code class=\"xref py py-attr docutils literal notranslate\">parent_link=True</code></a> on <code class=\"docutils literal notranslate\">Restaurant</code>.</p>\n<section id=\"meta-and-multi-table-inheritance\">\n<span id=\"id9\"></span><h4><code class=\"docutils literal notranslate\">Meta</code> and multi-table inheritance<a class=\"heading-anchor\" href=\"#meta-and-multi-table-inheritance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>In the multi-table inheritance situation, it doesn't make sense for a child\nclass to inherit from its parent's <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class. All the <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> options\nhave already been applied to the parent class and applying them again would\nnormally only lead to contradictory behavior (this is in contrast with the\nabstract base class case, where the base class doesn't exist in its own\nright).</p>\n<p>So a child model does not have access to its parent's <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class. However, there are a few limited cases where the child\ninherits behavior from the parent: if the child does not specify an\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.ordering\" title=\"django.db.models.Options.ordering\"><code class=\"xref py py-attr docutils literal notranslate\">ordering</code></a> attribute or a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.get_latest_by\" title=\"django.db.models.Options.get_latest_by\"><code class=\"xref py py-attr docutils literal notranslate\">get_latest_by</code></a> attribute, it will inherit\nthese from its parent.</p>\n<p>If the parent has an ordering and you don't want the child to have any natural\nordering, you can explicitly disable it:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">ChildModel</span><span class=\"p\">(</span>ParentModel<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        <span class=\"c1\"># Remove parent&#39;s ordering effect</span>\n        ordering <span class=\"o\">=</span> <span class=\"p\">[]</span>\n</code></pre></div>\n</section>\n<section id=\"inheritance-and-reverse-relations\">\n<h4>Inheritance and reverse relations<a class=\"heading-anchor\" href=\"#inheritance-and-reverse-relations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Because multi-table inheritance uses an implicit\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> to link the child and\nthe parent, it's possible to move from the parent down to the child,\nas in the above example. However, this uses up the name that is the\ndefault <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a> value for\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a> relations.  If you\nare putting those types of relations on a subclass of the parent model, you\n<strong>must</strong> specify the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name\" title=\"django.db.models.ForeignKey.related_name\"><code class=\"xref py py-attr docutils literal notranslate\">related_name</code></a>\nattribute on each such field. If you forget, Django will raise a validation\nerror.</p>\n<p>For example, using the above <code class=\"docutils literal notranslate\">Place</code> class again, let's create another\nsubclass with a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ManyToManyField\" title=\"django.db.models.ManyToManyField\"><code class=\"xref py py-class docutils literal notranslate\">ManyToManyField</code></a>:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Supplier</span><span class=\"p\">(</span>Place<span class=\"p\">):</span>\n    customers <span class=\"o\">=</span> models<span class=\"o\">.</span>ManyToManyField<span class=\"p\">(</span>Place<span class=\"p\">)</span>\n</code></pre></div>\n<p>This results in the error:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>Reverse query name <span class=\"k\">for</span> <span class=\"s1\">&#39;Supplier.customers&#39;</span> clashes <span class=\"k\">with</span> reverse query\nname <span class=\"k\">for</span> <span class=\"s1\">&#39;Supplier.place_ptr&#39;</span><span class=\"o\">.</span>\n\nHINT<span class=\"p\">:</span> Add <span class=\"ow\">or</span> change a related_name argument to the definition <span class=\"k\">for</span>\n<span class=\"s1\">&#39;Supplier.customers&#39;</span> <span class=\"ow\">or</span> <span class=\"s1\">&#39;Supplier.place_ptr&#39;</span><span class=\"o\">.</span>\n</code></pre></div>\n<p>Adding <code class=\"docutils literal notranslate\">related_name</code> to the <code class=\"docutils literal notranslate\">customers</code> field as follows would resolve the\nerror: <code class=\"docutils literal notranslate\">models.ManyToManyField(Place, related_name='provider')</code>.</p>\n</section>\n<section id=\"specifying-the-parent-link-field\">\n<h4>Specifying the parent link field<a class=\"heading-anchor\" href=\"#specifying-the-parent-link-field\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>As mentioned, Django will automatically create a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> linking your child\nclass back to any non-abstract parent models. If you want to control the\nname of the attribute linking back to the parent, you can create your\nown <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> and set\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField.parent_link\" title=\"django.db.models.OneToOneField.parent_link\"><code class=\"xref py py-attr docutils literal notranslate\">parent_link=True</code></a>\nto indicate that your field is the link back to the parent class.</p>\n</section>\n</section>\n<section id=\"proxy-models\">\n<span id=\"id10\"></span><h3>Proxy models<a class=\"heading-anchor\" href=\"#proxy-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When using <a class=\"reference internal\" href=\"#multi-table-inheritance\"><span class=\"std std-ref\">multi-table inheritance</span></a>, a new\ndatabase table is created for each subclass of a model. This is usually the\ndesired behavior, since the subclass needs a place to store any additional\ndata fields that are not present on the base class. Sometimes, however, you\nonly want to change the Python behavior of a model -- perhaps to change the\ndefault manager, or add a new method.</p>\n<p>This is what proxy model inheritance is for: creating a <em>proxy</em> for the\noriginal model. You can create, delete and update instances of the proxy model\nand all the data will be saved as if you were using the original (non-proxied)\nmodel. The difference is that you can change things like the default model\nordering or the default manager in the proxy, without having to alter the\noriginal.</p>\n<p>Proxy models are declared like normal models. You tell Django that it's a\nproxy model by setting the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.proxy\" title=\"django.db.models.Options.proxy\"><code class=\"xref py py-attr docutils literal notranslate\">proxy</code></a> attribute of\nthe <code class=\"docutils literal notranslate\">Meta</code> class to <code class=\"docutils literal notranslate\">True</code>.</p>\n<p>For example, suppose you want to add a method to the <code class=\"docutils literal notranslate\">Person</code> model. You can do it like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n    last_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">30</span><span class=\"p\">)</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">MyPerson</span><span class=\"p\">(</span>Person<span class=\"p\">):</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        proxy <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">do_something</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># ...</span>\n        <span class=\"k\">pass</span>\n</code></pre></div>\n<p>The <code class=\"docutils literal notranslate\">MyPerson</code> class operates on the same database table as its parent\n<code class=\"docutils literal notranslate\">Person</code> class. In particular, any new instances of <code class=\"docutils literal notranslate\">Person</code> will also be\naccessible through <code class=\"docutils literal notranslate\">MyPerson</code>, and vice-versa:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>p <span class=\"o\">=</span> Person<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>first_name<span class=\"o\">=</span><span class=\"s2\">&quot;foobar&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>MyPerson<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>first_name<span class=\"o\">=</span><span class=\"s2\">&quot;foobar&quot;</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;MyPerson: foobar&gt;</span>\n</code></pre></div>\n<p>你仍然可以使用一个代理模型来定义模型的默认排序方法。你也许不会想一直对“Persion”进行排序，但是通常情况下用代理模型根据“last_name”属性进行排序。这很简单:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">OrderedPerson</span><span class=\"p\">(</span>Person<span class=\"p\">):</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        ordering <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"s2\">&quot;last_name&quot;</span><span class=\"p\">]</span>\n        proxy <span class=\"o\">=</span> <span class=\"kc\">True</span>\n</code></pre></div>\n<p>Now normal <code class=\"docutils literal notranslate\">Person</code> queries will be unordered\nand <code class=\"docutils literal notranslate\">OrderedPerson</code> queries will be ordered by <code class=\"docutils literal notranslate\">last_name</code>.</p>\n<p>代理模型继承“Meta”属性:ref:和普通模型使用同样的方法&lt;meta-and-multi-table-inheritance&gt;。</p>\n<section id=\"querysets-still-return-the-model-that-was-requested\">\n<h4><code class=\"docutils literal notranslate\">QuerySet</code>s still return the model that was requested<a class=\"heading-anchor\" href=\"#querysets-still-return-the-model-that-was-requested\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There is no way to have Django return, say, a <code class=\"docutils literal notranslate\">MyPerson</code> object whenever you\nquery for <code class=\"docutils literal notranslate\">Person</code> objects. A queryset for <code class=\"docutils literal notranslate\">Person</code> objects will return\nthose types of objects. The whole point of proxy objects is that code relying\non the original <code class=\"docutils literal notranslate\">Person</code> will use those and your own code can use the\nextensions you included (that no other code is relying on anyway). It is not\na way to replace the <code class=\"docutils literal notranslate\">Person</code> (or any other) model everywhere with something\nof your own creation.</p>\n</section>\n<section id=\"base-class-restrictions\">\n<h4>Base class restrictions<a class=\"heading-anchor\" href=\"#base-class-restrictions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>一个代理模型必须仅能继承一个非抽象模型类。你不能继承多个非抽象模型类，因为代理模型无法提供不同数据表的任何行间连接。一个代理模型可以继承任意数量的抽象模型类，假如他们*没有*定义任何的模型字段。一个代理模型也可以继承任意数量的代理模型，只需他们共享同一个非抽象父类。</p>\n</section>\n<section id=\"proxy-model-managers\">\n<h4>代理模型管理器<a class=\"heading-anchor\" href=\"#proxy-model-managers\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If you don't specify any model managers on a proxy model, it inherits the\nmanagers from its model parents. If you define a manager on the proxy model,\nit will become the default, although any managers defined on the parent\nclasses will still be available.</p>\n<p>Continuing our example from above, you could change the default manager used\nwhen you query the <code class=\"docutils literal notranslate\">Person</code> model like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n<span class=\"k\">class</span> <span class=\"nc\">NewManager</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Manager<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">pass</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">MyPerson</span><span class=\"p\">(</span>Person<span class=\"p\">):</span>\n    objects <span class=\"o\">=</span> NewManager<span class=\"p\">()</span>\n\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        proxy <span class=\"o\">=</span> <span class=\"kc\">True</span>\n</code></pre></div>\n<p>If you wanted to add a new manager to the Proxy, without replacing the\nexisting default, you can use the techniques described in the <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/managers/#custom-managers-and-inheritance\"><span class=\"std std-ref\">custom\nmanager</span></a> documentation: create a base class\ncontaining the new managers and inherit that after the primary base class:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Create an abstract class for the new manager.</span>\n<span class=\"k\">class</span> <span class=\"nc\">ExtraManagers</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    secondary <span class=\"o\">=</span> NewManager<span class=\"p\">()</span>\n\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        abstract <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">MyPerson</span><span class=\"p\">(</span>Person<span class=\"p\">,</span> ExtraManagers<span class=\"p\">):</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        proxy <span class=\"o\">=</span> <span class=\"kc\">True</span>\n</code></pre></div>\n<p>通常情况下，你可能不需要这么做。然而，你需要的时候，这也是可以的。</p>\n</section>\n<section id=\"differences-between-proxy-inheritance-and-unmanaged-models\">\n<span id=\"proxy-vs-unmanaged-models\"></span><h4>Differences between proxy inheritance and unmanaged models<a class=\"heading-anchor\" href=\"#differences-between-proxy-inheritance-and-unmanaged-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Proxy model inheritance might look fairly similar to creating an unmanaged\nmodel, using the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.managed\" title=\"django.db.models.Options.managed\"><code class=\"xref py py-attr docutils literal notranslate\">managed</code></a> attribute on a\nmodel's <code class=\"docutils literal notranslate\">Meta</code> class.</p>\n<p>With careful setting of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/options/#django.db.models.Options.db_table\" title=\"django.db.models.Options.db_table\"><code class=\"xref py py-attr docutils literal notranslate\">Meta.db_table</code></a> you could create an unmanaged model that\nshadows an existing model and adds Python methods to it. However, that would be\nvery repetitive and fragile as you need to keep both copies synchronized if you\nmake any changes.</p>\n<p>On the other hand, proxy models are intended to behave exactly like the model\nthey are proxying for. They are always in sync with the parent model since they\ndirectly inherit its fields and managers.</p>\n<p>The general rules are:</p>\n<ol class=\"arabic simple\">\n<li><p>If you are mirroring an existing model or database table and don't want\nall the original database table columns, use <code class=\"docutils literal notranslate\">Meta.managed=False</code>.\nThat option is normally useful for modeling database views and tables\nnot under the control of Django.</p></li>\n<li><p>If you are wanting to change the Python-only behavior of a model, but\nkeep all the same fields as in the original, use <code class=\"docutils literal notranslate\">Meta.proxy=True</code>.\nThis sets things up so that the proxy model is an exact copy of the\nstorage structure of the original model when data is saved.</p></li>\n</ol>\n</section>\n</section>\n<section id=\"multiple-inheritance\">\n<span id=\"model-multiple-inheritance-topic\"></span><h3>Multiple inheritance<a class=\"heading-anchor\" href=\"#multiple-inheritance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Just as with Python's subclassing, it's possible for a Django model to inherit\nfrom multiple parent models. Keep in mind that normal Python name resolution\nrules apply. The first base class that a particular name (e.g. <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a>) appears in will be the one that is used; for example, this\nmeans that if multiple parents contain a <a class=\"reference internal\" href=\"#meta-options\"><span class=\"std std-ref\">Meta</span></a> class,\nonly the first one is going to be used, and all others will be ignored.</p>\n<p>Generally, you won't need to inherit from multiple parents. The main use-case\nwhere this is useful is for &quot;mix-in&quot; classes: adding a particular extra\nfield or method to every class that inherits the mix-in. Try to keep your\ninheritance hierarchies as simple and straightforward as possible so that you\nwon't have to struggle to work out where a particular piece of information is\ncoming from.</p>\n<p>Note that inheriting from multiple models that have a common <code class=\"docutils literal notranslate\">id</code> primary\nkey field will raise an error. To properly use multiple inheritance, you can\nuse an explicit <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a> in the base models:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Article</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    article_id <span class=\"o\">=</span> models<span class=\"o\">.</span>AutoField<span class=\"p\">(</span>primary_key<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n    <span class=\"o\">...</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Book</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    book_id <span class=\"o\">=</span> models<span class=\"o\">.</span>AutoField<span class=\"p\">(</span>primary_key<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n    <span class=\"o\">...</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">BookReview</span><span class=\"p\">(</span>Book<span class=\"p\">,</span> Article<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n</code></pre></div>\n<p>Or use a common ancestor to hold the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a>. This\nrequires using an explicit <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.OneToOneField\" title=\"django.db.models.OneToOneField\"><code class=\"xref py py-class docutils literal notranslate\">OneToOneField</code></a> from each\nparent model to the common ancestor to avoid a clash between the fields that\nare automatically generated and inherited by the child:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Piece</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Article</span><span class=\"p\">(</span>Piece<span class=\"p\">):</span>\n    article_piece <span class=\"o\">=</span> models<span class=\"o\">.</span>OneToOneField<span class=\"p\">(</span>Piece<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span> parent_link<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n    <span class=\"o\">...</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">Book</span><span class=\"p\">(</span>Piece<span class=\"p\">):</span>\n    book_piece <span class=\"o\">=</span> models<span class=\"o\">.</span>OneToOneField<span class=\"p\">(</span>Piece<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">,</span> parent_link<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n    <span class=\"o\">...</span>\n\n<span class=\"k\">class</span> <span class=\"nc\">BookReview</span><span class=\"p\">(</span>Book<span class=\"p\">,</span> Article<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n</code></pre></div>\n</section>\n<section id=\"field-name-hiding-is-not-permitted\">\n<h3>Field name &quot;hiding&quot; is not permitted<a class=\"heading-anchor\" href=\"#field-name-hiding-is-not-permitted\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>In normal Python class inheritance, it is permissible for a child class to\noverride any attribute from the parent class. In Django, this isn't usually\npermitted for model fields. If a non-abstract model base class has a field\ncalled <code class=\"docutils literal notranslate\">author</code>, you can't create another model field or define\nan attribute called <code class=\"docutils literal notranslate\">author</code> in any class that inherits from that base class.</p>\n<p>This restriction doesn't apply to model fields inherited from an abstract\nmodel. Such fields may be overridden with another field or value, or be removed\nby setting <code class=\"docutils literal notranslate\">field_name = None</code>.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>Model managers are inherited from abstract base classes. Overriding an\ninherited field which is referenced by an inherited\n<a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/managers/#django.db.models.Manager\" title=\"django.db.models.Manager\"><code class=\"xref py py-class docutils literal notranslate\">Manager</code></a> may cause subtle bugs. See <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/managers/#custom-managers-and-inheritance\"><span class=\"std std-ref\">custom\nmanagers and model inheritance</span></a>.</p>\n</aside>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>Some fields define extra attributes on the model, e.g. a\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a> defines an extra attribute with\n<code class=\"docutils literal notranslate\">_id</code> appended to the field name, as well as <code class=\"docutils literal notranslate\">related_name</code> and\n<code class=\"docutils literal notranslate\">related_query_name</code> on the foreign model.</p>\n<p>These extra attributes cannot be overridden unless the field that defines\nit is changed or removed so that it no longer defines the extra attribute.</p>\n</aside>\n<p>Overriding fields in a parent model leads to difficulties in areas such as\ninitializing new instances (specifying which field is being initialized in\n<code class=\"docutils literal notranslate\">Model.__init__</code>) and serialization. These are features which normal Python\nclass inheritance doesn't have to deal with in quite the same way, so the\ndifference between Django model inheritance and Python class inheritance isn't\narbitrary.</p>\n<p>This restriction only applies to attributes which are\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> instances. Normal Python attributes\ncan be overridden if you wish. It also only applies to the name of the\nattribute as Python sees it: if you are manually specifying the database\ncolumn name, you can have the same column name appearing in both a child and\nan ancestor model for multi-table inheritance (they are columns in two\ndifferent database tables).</p>\n<p>Django will raise a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/exceptions/#django.core.exceptions.FieldError\" title=\"django.core.exceptions.FieldError\"><code class=\"xref py py-exc docutils literal notranslate\">FieldError</code></a> if you override\nany model field in any ancestor model.</p>\n</section>\n</section>\n<section id=\"organizing-models-in-a-package\">\n<h2>Organizing models in a package<a class=\"heading-anchor\" href=\"#organizing-models-in-a-package\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/django-admin/#django-admin-startapp\"><code class=\"xref std std-djadmin docutils literal notranslate\">manage.py startapp</code></a> command creates an application\nstructure that includes a <code class=\"docutils literal notranslate\">models.py</code> file. If you have many models,\norganizing them in separate files may be useful.</p>\n<p>To do so, create a <code class=\"docutils literal notranslate\">models</code> package. Remove <code class=\"docutils literal notranslate\">models.py</code> and create a\n<code class=\"docutils literal notranslate\">myapp/models/</code> directory with an <code class=\"docutils literal notranslate\">__init__.py</code> file and the files to\nstore your models. You must import the models in the <code class=\"docutils literal notranslate\">__init__.py</code> file.</p>\n<p>For example, if you had <code class=\"docutils literal notranslate\">organic.py</code> and <code class=\"docutils literal notranslate\">synthetic.py</code> in the <code class=\"docutils literal notranslate\">models</code>\ndirectory:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"default\"><figcaption class=\"code-block-caption\"><code>myapp/models/__init__.py</code></figcaption><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"myapp/models/__init__.py\"><code><span class=\"kn\">from</span> <span class=\"nn\">.organic</span> <span class=\"kn\">import</span> Person\n<span class=\"kn\">from</span> <span class=\"nn\">.synthetic</span> <span class=\"kn\">import</span> Robot\n</code></pre></figure>\n<p>Explicitly importing each model rather than using <code class=\"docutils literal notranslate\">from .models import *</code>\nhas the advantages of not cluttering the namespace, making code more readable,\nand keeping code analysis tools useful.</p>\n<aside class=\"admonition admonition-seealso\" role=\"note\">\n<p class=\"admonition-title\">See also</p>\n<dl class=\"simple\">\n<dt><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/\"><span class=\"doc\">The Models Reference</span></a></dt><dd><p>Covers all the model related APIs including model fields, related\nobjects, and <code class=\"docutils literal notranslate\">QuerySet</code>.</p>\n</dd>\n</dl>\n</aside>\n</section>","rootId":"module-django.db.models","toc":[{"title":"快速上手","anchor":"quick-example","children":[]},{"title":"使用模型","anchor":"using-models","children":[]},{"title":"字段","anchor":"fields","children":[{"title":"字段类型","anchor":"field-types","children":[]},{"title":"Field options","anchor":"field-options","children":[]},{"title":"Automatic primary key fields","anchor":"automatic-primary-key-fields","children":[]},{"title":"Verbose field names","anchor":"verbose-field-names","children":[]},{"title":"Relationships","anchor":"relationships","children":[{"title":"Many-to-one relationships","anchor":"many-to-one-relationships","children":[]},{"title":"Many-to-many relationships","anchor":"many-to-many-relationships","children":[]},{"title":"Extra fields on many-to-many relationships","anchor":"extra-fields-on-many-to-many-relationships","children":[]},{"title":"One-to-one relationships","anchor":"one-to-one-relationships","children":[]}]},{"title":"Models across files","anchor":"models-across-files","children":[]},{"title":"Field name restrictions","anchor":"field-name-restrictions","children":[]},{"title":"Custom field types","anchor":"custom-field-types","children":[]}]},{"title":"Meta options","anchor":"meta-options","children":[]},{"title":"Model attributes","anchor":"model-attributes","children":[]},{"title":"Model methods","anchor":"model-methods","children":[{"title":"Overriding predefined model methods","anchor":"overriding-predefined-model-methods","children":[]},{"title":"Executing custom SQL","anchor":"executing-custom-sql","children":[]}]},{"title":"模型继承","anchor":"model-inheritance","children":[{"title":"Abstract base classes","anchor":"abstract-base-classes","children":[{"title":"Meta inheritance","anchor":"meta-inheritance","children":[]},{"title":"Be careful with related_name and related_query_name","anchor":"be-careful-with-related-name-and-related-query-name","children":[]}]},{"title":"Multi-table inheritance","anchor":"multi-table-inheritance","children":[{"title":"Meta and multi-table inheritance","anchor":"meta-and-multi-table-inheritance","children":[]},{"title":"Inheritance and reverse relations","anchor":"inheritance-and-reverse-relations","children":[]},{"title":"Specifying the parent link field","anchor":"specifying-the-parent-link-field","children":[]}]},{"title":"Proxy models","anchor":"proxy-models","children":[{"title":"QuerySets still return the model that was requested","anchor":"querysets-still-return-the-model-that-was-requested","children":[]},{"title":"Base class restrictions","anchor":"base-class-restrictions","children":[]},{"title":"代理模型管理器","anchor":"proxy-model-managers","children":[]},{"title":"Differences between proxy inheritance and unmanaged models","anchor":"differences-between-proxy-inheritance-and-unmanaged-models","children":[]}]},{"title":"Multiple inheritance","anchor":"multiple-inheritance","children":[]},{"title":"Field name \"hiding\" is not permitted","anchor":"field-name-hiding-is-not-permitted","children":[]}]},{"title":"Organizing models in a package","anchor":"organizing-models-in-a-package","children":[]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/zh-hans/2.0/topics/"},{"docname":"topics/db/index","title":"模型和数据库","url":"/zh-hans/2.0/topics/db/"}],"prev":{"docname":"topics/db/index","title":"模型和数据库","url":"/zh-hans/2.0/topics/db/"},"next":{"docname":"topics/db/queries","title":"Making queries","url":"/zh-hans/2.0/topics/db/queries/"},"formats":{"html":"/zh-hans/2.0/topics/db/models/","markdown":"/zh-hans/2.0/topics/db/models.md","json":"/zh-hans/2.0/topics/db/models.json"},"source":"https://github.com/django/django/blob/stable/2.0.x/docs/topics/db/models.txt","official":"https://docs.djangoproject.com/zh-hans/2.0/topics/db/models/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}