Sophie

Sophie

distrib > Arklinux > devel > i586 > media > main > by-pkgid > 5fcb1fedf34660bc240dc59b7bfcebc4 > files > 438

django-doc-1.2.3-1ark.noarch.rpm


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Models &mdash; Django v1.2 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django v1.2 documentation" href="../../index.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Making queries" href="queries.html" />
    <link rel="prev" title="Models and databases" href="index.html" />
 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>

  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django v1.2 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="Models and databases">previous</a> 
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="queries.html" title="Making queries">next</a> &raquo;</div>
    </div>
    
    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-models">
            
  <div class="section" id="s-module-django.db.models">
<span id="s-models"></span><span id="module-django.db.models"></span><span id="models"></span><h1>Models<a class="headerlink" href="#module-django.db.models" title="Permalink to this headline">¶</a></h1>
<p>A model is the single, definitive source of data about your data. It contains
the essential fields and behaviors of the data you&#8217;re storing. Generally, each
model maps to a single database table.</p>
<p>The basics:</p>
<ul class="simple">
<li>Each model is a Python class that subclasses
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model" title="django.db.models.Model"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Model</span></tt></a>.</li>
<li>Each attribute of the model represents a database field.</li>
<li>With all of this, Django gives you an automatically-generated
database-access API; see <a class="reference internal" href="queries.html"><em>Making queries</em></a>.</li>
</ul>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">A companion to this document is the <a class="reference external" href="http://www.djangoproject.com/documentation/models/">official repository of model
examples</a>. (In the Django source distribution, these examples are in the
<tt class="docutils literal"><span class="pre">tests/modeltests</span></tt> directory.)</p>
</div>
<div class="section" id="s-quick-example">
<span id="quick-example"></span><h2>Quick example<a class="headerlink" href="#quick-example" title="Permalink to this headline">¶</a></h2>
<p>This example model defines a <tt class="docutils literal"><span class="pre">Person</span></tt>, which has a <tt class="docutils literal"><span class="pre">first_name</span></tt> and
<tt class="docutils literal"><span class="pre">last_name</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">first_name</span></tt> and <tt class="docutils literal"><span class="pre">last_name</span></tt> are <a class="reference internal" href="#fields">fields</a> of the model. Each field is
specified as a class attribute, and each attribute maps to a database column.</p>
<p>The above <tt class="docutils literal"><span class="pre">Person</span></tt> model would create a database table like this:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">myapp_person</span> <span class="p">(</span>
    <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>
    <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>
    <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>
<span class="p">);</span>
</pre></div>
</div>
<p>Some technical notes:</p>
<ul class="simple">
<li>The name of the table, <tt class="docutils literal"><span class="pre">myapp_person</span></tt>, is automatically derived from
some model metadata but can be overridden. See <a class="reference internal" href="../../ref/models/options.html#table-names"><em>Table names</em></a> for more
details..</li>
<li>An <tt class="docutils literal"><span class="pre">id</span></tt> field is added automatically, but this behavior can be
overridden. See <a class="reference internal" href="#automatic-primary-key-fields"><em>Automatic primary key fields</em></a>.</li>
<li>The <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></tt> SQL in this example is formatted using PostgreSQL
syntax, but it's worth noting Django uses SQL tailored to the database
backend specified in your <a class="reference internal" href="../settings.html"><em>settings file</em></a>.</li>
</ul>
</div>
<div class="section" id="s-using-models">
<span id="using-models"></span><h2>Using models<a class="headerlink" href="#using-models" title="Permalink to this headline">¶</a></h2>
<p>Once you have defined your models, you need to tell Django you're going to <em>use</em>
those models. Do this by editing your settings file and changing the
<a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting to add the name of the module that contains
your <tt class="docutils literal"><span class="pre">models.py</span></tt>.</p>
<p>For example, if the models for your application live in the module
<tt class="docutils literal"><span class="pre">mysite.myapp.models</span></tt> (the package structure that is created for an
application by the <a class="reference internal" href="../../ref/django-admin.html#django-admin-startapp"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">startapp</span></tt></a> script),
<a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> should read, in part:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">(</span>
    <span class="c">#...</span>
    <span class="s">&#39;mysite.myapp&#39;</span><span class="p">,</span>
    <span class="c">#...</span>
<span class="p">)</span>
</pre></div>
</div>
<p>When you add new apps to <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, be sure to run
<a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">manage.py</span> <span class="pre">syncdb</span></tt></a>.</p>
</div>
<div class="section" id="s-fields">
<span id="fields"></span><h2>Fields<a class="headerlink" href="#fields" title="Permalink to this headline">¶</a></h2>
<p>The most important part of a model -- and the only required part of a model --
is the list of database fields it defines. Fields are specified by class
attributes.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Musician</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">instrument</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">artist</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Musician</span><span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">release_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">num_stars</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="s-field-types">
<span id="field-types"></span><h3>Field types<a class="headerlink" href="#field-types" title="Permalink to this headline">¶</a></h3>
<p>Each field in your model should be an instance of the appropriate
<a class="reference internal" href="../../howto/custom-model-fields.html#django.db.models.django.db.models.Field" title="django.db.models.django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class. Django uses the field class types to
determine a few things:</p>
<ul class="simple">
<li>The database column type (e.g. <tt class="docutils literal"><span class="pre">INTEGER</span></tt>, <tt class="docutils literal"><span class="pre">VARCHAR</span></tt>).</li>
<li>The widget to use in Django's admin interface, if you care to use it
(e.g. <tt class="docutils literal"><span class="pre">&lt;input</span> <span class="pre">type=&quot;text&quot;&gt;</span></tt>, <tt class="docutils literal"><span class="pre">&lt;select&gt;</span></tt>).</li>
<li>The minimal validation requirements, used in Django's admin and in
automatically-generated forms.</li>
</ul>
<p>Django ships with dozens of built-in field types; you can find the complete list
in the <a class="reference internal" href="../../ref/models/fields.html#model-field-types"><em>model field reference</em></a>. You can easily write
your own fields if Django's built-in ones don't do the trick; see
<a class="reference internal" href="../../howto/custom-model-fields.html"><em>Writing custom model fields</em></a>.</p>
</div>
<div class="section" id="s-field-options">
<span id="field-options"></span><h3>Field options<a class="headerlink" href="#field-options" title="Permalink to this headline">¶</a></h3>
<p>Each field takes a certain set of field-specific arguments (documented in the
<a class="reference internal" href="../../ref/models/fields.html#model-field-types"><em>model field reference</em></a>). For example,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> (and its subclasses) require a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><tt class="xref py py-attr docutils literal"><span class="pre">max_length</span></tt></a> argument which specifies the size
of the <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> database field used to store the data.</p>
<p>There's also a set of common arguments available to all field types. All are
optional. They're fully explained in the <a class="reference internal" href="../../ref/models/fields.html#common-model-field-options"><em>reference</em></a>, but here's a quick summary of the most often-used
ones:</p>
<dl class="docutils">
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a></dt>
<dd>If <tt class="xref docutils literal"><span class="pre">True</span></tt>, Django will store empty values as <tt class="docutils literal"><span class="pre">NULL</span></tt> in the database.
Default is <tt class="xref docutils literal"><span class="pre">False</span></tt>.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a></dt>
<dd><p class="first">If <tt class="xref docutils literal"><span class="pre">True</span></tt>, the field is allowed to be blank. Default is <tt class="xref docutils literal"><span class="pre">False</span></tt>.</p>
<p class="last">Note that this is different than <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a>.
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a> is purely database-related, whereas
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a> is validation-related. If a field has
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank=True</span></tt></a>, validation on Django's admin site will
allow entry of an empty value. If a field has <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank=False</span></tt></a>, the field will be required.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.choices" title="django.db.models.Field.choices"><tt class="xref py py-attr docutils literal"><span class="pre">choices</span></tt></a></dt>
<dd><p class="first">An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
this field. If this is given, Django's admin will use a select box
instead of the standard text field and will limit choices to the choices
given.</p>
<p>A choices list looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">YEAR_IN_SCHOOL_CHOICES</span> <span class="o">=</span> <span class="p">(</span>
    <span class="p">(</span><span class="s">u&#39;FR&#39;</span><span class="p">,</span> <span class="s">u&#39;Freshman&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">u&#39;SO&#39;</span><span class="p">,</span> <span class="s">u&#39;Sophomore&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">u&#39;JR&#39;</span><span class="p">,</span> <span class="s">u&#39;Junior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">u&#39;SR&#39;</span><span class="p">,</span> <span class="s">u&#39;Senior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s">u&#39;GR&#39;</span><span class="p">,</span> <span class="s">u&#39;Graduate&#39;</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>The first element in each tuple is the value that will be stored in the
database, the second element will be displayed by the admin interface,
or in a ModelChoiceField. Given an instance of a model object, the
display value for a choices field can be accessed using the
<tt class="docutils literal"><span class="pre">get_FOO_display</span></tt> method. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">GENDER_CHOICES</span> <span class="o">=</span> <span class="p">(</span>
        <span class="p">(</span><span class="s">u&#39;M&#39;</span><span class="p">,</span> <span class="s">u&#39;Male&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="s">u&#39;F&#39;</span><span class="p">,</span> <span class="s">u&#39;Female&#39;</span><span class="p">),</span>
    <span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
    <span class="n">gender</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">GENDER_CHOICES</span><span class="p">)</span>
</pre></div>
</div>
<div class="last highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Fred Flinstone&quot;</span><span class="p">,</span> <span class="n">gender</span><span class="o">=</span><span class="s">&quot;M&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">gender</span>
<span class="go">u&#39;M&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">get_gender_display</span><span class="p">()</span>
<span class="go">u&#39;Male&#39;</span>
</pre></div>
</div>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><tt class="xref py py-attr docutils literal"><span class="pre">default</span></tt></a></dt>
<dd>The default value for the field. This can be a value or a callable
object. If callable it will be called every time a new object is
created.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><tt class="xref py py-attr docutils literal"><span class="pre">help_text</span></tt></a></dt>
<dd>Extra &quot;help&quot; text to be displayed under the field on the object's admin
form. It's useful for documentation even if your object doesn't have an
admin form.</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a></dt>
<dd><p class="first">If <tt class="xref docutils literal"><span class="pre">True</span></tt>, this field is the primary key for the model.</p>
<p class="last">If you don't specify <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> for
any fields in your model, Django will automatically add an
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.IntegerField" title="django.db.models.IntegerField"><tt class="xref py py-class docutils literal"><span class="pre">IntegerField</span></tt></a> to hold the primary key, so you don't need to set
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> on any of your fields
unless you want to override the default primary-key behavior. For more,
see <a class="reference internal" href="#automatic-primary-key-fields"><em>Automatic primary key fields</em></a>.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><tt class="xref py py-attr docutils literal"><span class="pre">unique</span></tt></a></dt>
<dd>If <tt class="xref docutils literal"><span class="pre">True</span></tt>, this field must be unique throughout the table.</dd>
</dl>
<p>Again, these are just short descriptions of the most common field options. Full
details can be found in the <a class="reference internal" href="../../ref/models/fields.html#common-model-field-options"><em>common model field option reference</em></a>.</p>
</div>
<div class="section" id="s-automatic-primary-key-fields">
<span id="s-id1"></span><span id="automatic-primary-key-fields"></span><span id="id1"></span><h3>Automatic primary key fields<a class="headerlink" href="#automatic-primary-key-fields" title="Permalink to this headline">¶</a></h3>
<p>By default, Django gives each model the following field:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">AutoField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>This is an auto-incrementing primary key.</p>
<p>If you'd like to specify a custom primary key, just specify
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a> on one of your fields. If Django
sees you've explicitly set <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">Field.primary_key</span></tt></a>, it won't add the automatic
<tt class="docutils literal"><span class="pre">id</span></tt> column.</p>
<p>Each model requires exactly one field to have <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key=True</span></tt></a>.</p>
</div>
<div class="section" id="s-verbose-field-names">
<span id="s-id2"></span><span id="verbose-field-names"></span><span id="id2"></span><h3>Verbose field names<a class="headerlink" href="#verbose-field-names" title="Permalink to this headline">¶</a></h3>
<p>Each field type, except for <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> and
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a>, takes an optional first positional
argument -- a verbose name. If the verbose name isn't given, Django will
automatically create it using the field's attribute name, converting underscores
to spaces.</p>
<p>In this example, the verbose name is <tt class="docutils literal"><span class="pre">&quot;Person's</span> <span class="pre">first</span> <span class="pre">name&quot;</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="s">&quot;Person&#39;s first name&quot;</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p>In this example, the verbose name is <tt class="docutils literal"><span class="pre">&quot;first</span> <span class="pre">name&quot;</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> and
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> require the first argument to be a
model class, so use the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a> keyword argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">poll</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Poll</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;the related poll&quot;</span><span class="p">)</span>
<span class="n">sites</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Site</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;list of sites&quot;</span><span class="p">)</span>
<span class="n">place</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span><span class="n">Place</span><span class="p">,</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s">&quot;related place&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The convention is not to capitalize the first letter of the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a>. Django will automatically capitalize the first
letter where it needs to.</p>
</div>
<div class="section" id="s-relationships">
<span id="relationships"></span><h3>Relationships<a class="headerlink" href="#relationships" title="Permalink to this headline">¶</a></h3>
<p>Clearly, the power of relational databases lies in relating tables to each
other. Django offers ways to define the three most common types of database
relationships: many-to-one, many-to-many and one-to-one.</p>
<div class="section" id="s-many-to-one-relationships">
<span id="many-to-one-relationships"></span><h4>Many-to-one relationships<a class="headerlink" href="#many-to-one-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a many-to-one relationship, use <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>.
You use it just like any other <a class="reference internal" href="../../howto/custom-model-fields.html#django.db.models.django.db.models.Field" title="django.db.models.django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> type: by
including it as a class attribute of your model.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> requires a positional argument: the class
to which the model is related.</p>
<p>For example, if a <tt class="docutils literal"><span class="pre">Car</span></tt> model has a <tt class="docutils literal"><span class="pre">Manufacturer</span></tt> -- that is, a
<tt class="docutils literal"><span class="pre">Manufacturer</span></tt> makes multiple cars but each <tt class="docutils literal"><span class="pre">Car</span></tt> only has one
<tt class="docutils literal"><span class="pre">Manufacturer</span></tt> -- use the following definitions:</p>
<div class="highlight-python"><pre>class Manufacturer(models.Model):
    # ...

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer)
    # ...</pre>
</div>
<p>You can also create <a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationships</em></a> (an
object with a many-to-one relationship to itself) and <a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>relationships to
models not yet defined</em></a>; see <a class="reference internal" href="../../ref/models/fields.html#ref-foreignkey"><em>the model field
reference</em></a> for details.</p>
<p>It's suggested, but not required, that the name of a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> field (<tt class="docutils literal"><span class="pre">manufacturer</span></tt> in the example
above) be the name of the model, lowercase. You can, of course, call the field
whatever you want. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">company_that_makes_it</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Manufacturer</span><span class="p">)</span>
    <span class="c"># ...</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">See the <a class="reference external" href="http://www.djangoproject.com/documentation/models/many_to_one/">Many-to-one relationship model example</a> for a full example.</p>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> fields also accept a number of extra
arguments which are explained in <a class="reference internal" href="../../ref/models/fields.html#foreign-key-arguments"><em>the model field reference</em></a>. These options help define how the relationship should
work; all are optional.</p>
</div>
<div class="section" id="s-many-to-many-relationships">
<span id="many-to-many-relationships"></span><h4>Many-to-many relationships<a class="headerlink" href="#many-to-many-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a many-to-many relationship, use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>. You use it just like any other
<a class="reference internal" href="../../howto/custom-model-fields.html#django.db.models.django.db.models.Field" title="django.db.models.django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> type: by including it as a class attribute of
your model.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> requires a positional argument: the
class to which the model is related.</p>
<p>For example, if a <tt class="docutils literal"><span class="pre">Pizza</span></tt> has multiple <tt class="docutils literal"><span class="pre">Topping</span></tt> objects -- that is, a
<tt class="docutils literal"><span class="pre">Topping</span></tt> can be on multiple pizzas and each <tt class="docutils literal"><span class="pre">Pizza</span></tt> has multiple toppings
-- here's how you'd represent that:</p>
<div class="highlight-python"><pre>class Topping(models.Model):
    # ...

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)</pre>
</div>
<p>As with <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, you can also create
<a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationships</em></a> (an object with a
many-to-many relationship to itself) and <a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>relationships to models not yet
defined</em></a>; see <a class="reference internal" href="../../ref/models/fields.html#ref-manytomany"><em>the model field reference</em></a> for details.</p>
<p>It's suggested, but not required, that the name of a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> (<tt class="docutils literal"><span class="pre">toppings</span></tt> in the example above)
be a plural describing the set of related model objects.</p>
<p>It doesn't matter which model gets the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>, but you only need it in one of the
models -- not in both.</p>
<p>Generally, <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> instances should go in the
object that's going to be edited in the admin interface, if you're using
Django's admin. In the above example, <tt class="docutils literal"><span class="pre">toppings</span></tt> is in <tt class="docutils literal"><span class="pre">Pizza</span></tt> (rather than
<tt class="docutils literal"><span class="pre">Topping</span></tt> having a <tt class="docutils literal"><span class="pre">pizzas</span></tt> <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> )
because it's more natural to think about a pizza having toppings than a
topping being on multiple pizzas. The way it's set up above, the <tt class="docutils literal"><span class="pre">Pizza</span></tt> admin
form would let users select the toppings.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">See the <a class="reference external" href="http://www.djangoproject.com/documentation/models/many_to_many/">Many-to-many relationship model example</a> for a full example.</p>
</div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> fields also accept a number of extra
arguments which are explained in <a class="reference internal" href="../../ref/models/fields.html#manytomany-arguments"><em>the model field reference</em></a>. These options help define how the relationship should
work; all are optional.</p>
</div>
<div class="section" id="s-extra-fields-on-many-to-many-relationships">
<span id="s-intermediary-manytomany"></span><span id="extra-fields-on-many-to-many-relationships"></span><span id="intermediary-manytomany"></span><h4>Extra fields on many-to-many relationships<a class="headerlink" href="#extra-fields-on-many-to-many-relationships" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference internal" href="../../releases/1.0.html"><em>Please, see the release notes</em></a></div>
<p>When you're only dealing with simple many-to-many relationships such as
mixing and matching pizzas and toppings, a standard <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> is all you need. However, sometimes
you may need to associate data with the relationship between two models.</p>
<p>For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> to represent this relationship.
However, there is a lot of detail about the membership that you might want to
collect, such as the date at which the person joined the group.</p>
<p>For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> using the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.through" title="django.db.models.ManyToManyField.through"><tt class="xref py py-attr docutils literal"><span class="pre">through</span></tt></a> argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Group</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
    <span class="n">members</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">through</span><span class="o">=</span><span class="s">&#39;Membership&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Membership</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">person</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">)</span>
    <span class="n">group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Group</span><span class="p">)</span>
    <span class="n">date_joined</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">invite_reason</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span>
</pre></div>
</div>
<p>When you set up the intermediary model, you explicitly specify foreign
keys to the models that are involved in the ManyToMany relation. This
explicit declaration defines how the two models are related.</p>
<p>There are a few restrictions on the intermediate model:</p>
<ul class="simple">
<li>Your intermediate model must contain one - and <em>only</em> one - foreign key
to the target model (this would be <tt class="docutils literal"><span class="pre">Person</span></tt> in our example). If you
have more than one foreign key, a validation error will be raised.</li>
<li>Your intermediate model must contain one - and <em>only</em> one - foreign key
to the source model (this would be <tt class="docutils literal"><span class="pre">Group</span></tt> in our example). If you
have more than one foreign key, a validation error will be raised.</li>
<li>The only exception to this is a model which has a many-to-many
relationship to itself, through an intermediary model. In this
case, two foreign keys to the same model are permitted, but they
will be treated as the two (different) sides of the many-to-many
relation.</li>
<li>When defining a many-to-many relationship from a model to
itself, using an intermediary model, you <em>must</em> use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.symmetrical" title="django.db.models.ManyToManyField.symmetrical"><tt class="xref py py-attr docutils literal"><span class="pre">symmetrical=False</span></tt></a> (see
<a class="reference internal" href="../../ref/models/fields.html#manytomany-arguments"><em>the model field reference</em></a>).</li>
</ul>
<p>Now that you have set up your <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> to use
your intermediary model (<tt class="docutils literal"><span class="pre">Membership</span></tt>, in this case), you're ready to start
creating some many-to-many relationships. You do this by creating instances of
the intermediate model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">ringo</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Ringo Starr&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paul</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Paul McCartney&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span> <span class="o">=</span> <span class="n">Group</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;The Beatles&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m1</span> <span class="o">=</span> <span class="n">Membership</span><span class="p">(</span><span class="n">person</span><span class="o">=</span><span class="n">ringo</span><span class="p">,</span> <span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">date_joined</span><span class="o">=</span><span class="n">date</span><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>
<span class="gp">... </span>    <span class="n">invite_reason</span><span class="o">=</span> <span class="s">&quot;Needed a new drummer.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span><span class="o">.</span><span class="n">members</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Person: Ringo Starr&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringo</span><span class="o">.</span><span class="n">group_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Group: The Beatles&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span> <span class="o">=</span> <span class="n">Membership</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">person</span><span class="o">=</span><span class="n">paul</span><span class="p">,</span> <span class="n">group</span><span class="o">=</span><span class="n">beatles</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">date_joined</span><span class="o">=</span><span class="n">date</span><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>
<span class="gp">... </span>    <span class="n">invite_reason</span><span class="o">=</span> <span class="s">&quot;Wanted to form a band.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">beatles</span><span class="o">.</span><span class="n">members</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Person: Ringo Starr&gt;, &lt;Person: Paul McCartney&gt;]</span>
</pre></div>
</div>
<p>Unlike normal many-to-many fields, you <em>can't</em> use <tt class="docutils literal"><span class="pre">add</span></tt>, <tt class="docutils literal"><span class="pre">create</span></tt>,
or assignment (i.e., <tt class="docutils literal"><span class="pre">beatles.members</span> <span class="pre">=</span> <span class="pre">[...]</span></tt>) to create relationships:</p>
<div class="highlight-python"><pre># THIS WILL NOT WORK
&gt;&gt;&gt; beatles.members.add(john)
# NEITHER WILL THIS
&gt;&gt;&gt; beatles.members.create(name="George Harrison")
# AND NEITHER WILL THIS
&gt;&gt;&gt; beatles.members = [john, paul, ringo, george]</pre>
</div>
<p>Why? You can't just create a relationship between a <tt class="docutils literal"><span class="pre">Person</span></tt> and a <tt class="docutils literal"><span class="pre">Group</span></tt>
- you need to specify all the detail for the relationship required by the
<tt class="docutils literal"><span class="pre">Membership</span></tt> model. The simple <tt class="docutils literal"><span class="pre">add</span></tt>, <tt class="docutils literal"><span class="pre">create</span></tt> and assignment calls
don't provide a way to specify this extra detail. As a result, they are
disabled for many-to-many relationships that use an intermediate model.
The only way to create this type of relationship is to create instances of the
intermediate model.</p>
<p>The <tt class="docutils literal"><span class="pre">remove</span></tt> method is disabled for similar reasons. However, the
<tt class="docutils literal"><span class="pre">clear()</span></tt> method can be used to remove all many-to-many relationships
for an instance:</p>
<div class="highlight-python"><pre># Beatles have broken up
&gt;&gt;&gt; beatles.members.clear()</pre>
</div>
<p>Once you have established the many-to-many relationships by creating instances
of your intermediate model, you can issue queries. Just as with normal
many-to-many relationships, you can query using the attributes of the
many-to-many-related model:</p>
<div class="highlight-python"><pre># Find all the groups with a member whose name starts with 'Paul'
&gt;&gt;&gt; Group.objects.filter(members__name__startswith='Paul')
[&lt;Group: The Beatles&gt;]</pre>
</div>
<p>As you are using an intermediate model, you can also query on its attributes:</p>
<div class="highlight-python"><pre># Find all the members of the Beatles that joined after 1 Jan 1961
&gt;&gt;&gt; Person.objects.filter(
...     group__name='The Beatles',
...     membership__date_joined__gt=date(1961,1,1))
[&lt;Person: Ringo Starr]</pre>
</div>
</div>
<div class="section" id="s-one-to-one-relationships">
<span id="one-to-one-relationships"></span><h4>One-to-one relationships<a class="headerlink" href="#one-to-one-relationships" title="Permalink to this headline">¶</a></h4>
<p>To define a one-to-one relationship, use
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a>. You use it just like any other
<tt class="docutils literal"><span class="pre">Field</span></tt> type: by including it as a class attribute of your model.</p>
<p>This is most useful on the primary key of an object when that object &quot;extends&quot;
another object in some way.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> requires a positional argument: the
class to which the model is related.</p>
<p>For example, if you were building a database of &quot;places&quot;, you would
build pretty standard stuff such as address, phone number, etc. in the
database. Then, if you wanted to build a database of restaurants on
top of the places, instead of repeating yourself and replicating those
fields in the <tt class="docutils literal"><span class="pre">Restaurant</span></tt> model, you could make <tt class="docutils literal"><span class="pre">Restaurant</span></tt> have
a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> to <tt class="docutils literal"><span class="pre">Place</span></tt> (because a
restaurant &quot;is a&quot; place; in fact, to handle this you'd typically use
<a class="reference internal" href="#model-inheritance"><em>inheritance</em></a>, which involves an implicit
one-to-one relation).</p>
<p>As with <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, a
<a class="reference internal" href="../../ref/models/fields.html#recursive-relationships"><em>recursive relationship</em></a>
can be defined and
<a class="reference internal" href="../../ref/models/fields.html#lazy-relationships"><em>references to as-yet undefined models</em></a>
can be made; see <a class="reference internal" href="../../ref/models/fields.html#ref-onetoone"><em>the model field reference</em></a> for details.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">See the <a class="reference external" href="http://www.djangoproject.com/documentation/models/one_to_one/">One-to-one relationship model example</a> for a full example.</p>
</div>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference internal" href="../../releases/1.0.html"><em>Please, see the release notes</em></a></div>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> fields also accept one optional argument
described in the <a class="reference internal" href="../../ref/models/fields.html#ref-onetoone"><em>model field reference</em></a>.</p>
<p><a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> classes used to automatically become
the primary key on a model. This is no longer true (although you can manually
pass in the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a> argument if you like).
Thus, it's now possible to have multiple fields of type
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> on a single model.</p>
</div>
</div>
<div class="section" id="s-models-across-files">
<span id="models-across-files"></span><h3>Models across files<a class="headerlink" href="#models-across-files" title="Permalink to this headline">¶</a></h3>
<p>It's perfectly OK to relate a model to one from another app. To do this,
import the related model at the top of the model that holds your model. Then,
just refer to the other model class wherever needed. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">mysite.geography.models</span> <span class="kn">import</span> <span class="n">ZipCode</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">zip_code</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">ZipCode</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-field-name-restrictions">
<span id="field-name-restrictions"></span><h3>Field name restrictions<a class="headerlink" href="#field-name-restrictions" title="Permalink to this headline">¶</a></h3>
<p>Django places only two restrictions on model field names:</p>
<ol class="arabic">
<li><p class="first">A field name cannot be a Python reserved word, because that would result
in a Python syntax error. For example:</p>
<div class="highlight-python"><pre>class Example(models.Model):
    pass = models.IntegerField() # 'pass' is a reserved word!</pre>
</div>
</li>
<li><p class="first">A field name cannot contain more than one underscore in a row, due to
the way Django's query lookup syntax works. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Example</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">foo__bar</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span> <span class="c"># &#39;foo__bar&#39; has two underscores!</span>
</pre></div>
</div>
</li>
</ol>
<p>These limitations can be worked around, though, because your field name doesn't
necessarily have to match your database column name. See the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><tt class="xref py py-attr docutils literal"><span class="pre">db_column</span></tt></a> option.</p>
<p>SQL reserved words, such as <tt class="docutils literal"><span class="pre">join</span></tt>, <tt class="docutils literal"><span class="pre">where</span></tt> or <tt class="docutils literal"><span class="pre">select</span></tt>, <em>are</em> allowed as
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.</p>
</div>
<div class="section" id="s-custom-field-types">
<span id="custom-field-types"></span><h3>Custom field types<a class="headerlink" href="#custom-field-types" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference internal" href="../../releases/1.0.html"><em>Please, see the release notes</em></a></div>
<p>If one of the existing model fields cannot be used to fit your purposes, or if
you wish to take advantage of some less common database column types, you can
create your own field class. Full coverage of creating your own fields is
provided in <a class="reference internal" href="../../howto/custom-model-fields.html"><em>Writing custom model fields</em></a>.</p>
</div>
</div>
<div class="section" id="s-meta-options">
<span id="s-id3"></span><span id="meta-options"></span><span id="id3"></span><h2>Meta options<a class="headerlink" href="#meta-options" title="Permalink to this headline">¶</a></h2>
<p>Give your model metadata by using an inner <tt class="docutils literal"><span class="pre">class</span> <span class="pre">Meta</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Ox</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">horn_length</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;horn_length&quot;</span><span class="p">]</span>
        <span class="n">verbose_name_plural</span> <span class="o">=</span> <span class="s">&quot;oxen&quot;</span>
</pre></div>
</div>
<p>Model metadata is &quot;anything that's not a field&quot;, such as ordering options
(<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">ordering</span></tt></a>), database table name (<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-attr docutils literal"><span class="pre">db_table</span></tt></a>), or
human-readable singular and plural names (<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.verbose_name" title="django.db.models.Options.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a> and
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.verbose_name_plural" title="django.db.models.Options.verbose_name_plural"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name_plural</span></tt></a>). None are required, and adding <tt class="docutils literal"><span class="pre">class</span>
<span class="pre">Meta</span></tt> to a model is completely optional.</p>
<p>A complete list of all possible <tt class="docutils literal"><span class="pre">Meta</span></tt> options can be found in the <a class="reference internal" href="../../ref/models/options.html"><em>model
option reference</em></a>.</p>
</div>
<div class="section" id="s-model-methods">
<span id="s-id4"></span><span id="model-methods"></span><span id="id4"></span><h2>Model methods<a class="headerlink" href="#model-methods" title="Permalink to this headline">¶</a></h2>
<p>Define custom methods on a model to add custom &quot;row-level&quot; functionality to your
objects. Whereas <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">Manager</span></tt></a> methods are intended to do
&quot;table-wide&quot; things, model methods should act on a particular model instance.</p>
<p>This is a valuable technique for keeping business logic in one place -- the
model.</p>
<p>For example, this model has a few custom methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.contrib.localflavor.us.models</span> <span class="kn">import</span> <span class="n">USStateField</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">birth_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">address</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">city</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">state</span> <span class="o">=</span> <span class="n">USStateField</span><span class="p">()</span> <span class="c"># Yes, this is America-centric...</span>

    <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>
        <span class="s">&quot;Returns the person&#39;s baby-boomer status.&quot;</span>
        <span class="kn">import</span> <span class="nn">datetime</span>
        <span class="k">if</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><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> <span class="o">&lt;=</span> <span class="bp">self</span><span class="o">.</span><span class="n">birth_date</span> <span class="o">&lt;=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">1964</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">31</span><span class="p">):</span>
            <span class="k">return</span> <span class="s">&quot;Baby boomer&quot;</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">birth_date</span> <span class="o">&lt;</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><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>
            <span class="k">return</span> <span class="s">&quot;Pre-boomer&quot;</span>
        <span class="k">return</span> <span class="s">&quot;Post-boomer&quot;</span>

    <span class="k">def</span> <span class="nf">is_midwestern</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Returns True if this person is from the Midwest.&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">state</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;IL&#39;</span><span class="p">,</span> <span class="s">&#39;WI&#39;</span><span class="p">,</span> <span class="s">&#39;MI&#39;</span><span class="p">,</span> <span class="s">&#39;IN&#39;</span><span class="p">,</span> <span class="s">&#39;OH&#39;</span><span class="p">,</span> <span class="s">&#39;IA&#39;</span><span class="p">,</span> <span class="s">&#39;MO&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_get_full_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Returns the person&#39;s full name.&quot;</span>
        <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s"> </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">last_name</span><span class="p">)</span>
    <span class="n">full_name</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">_get_full_name</span><span class="p">)</span>
</pre></div>
</div>
<p>The last method in this example is a <a class="reference internal" href="../../glossary.html#term-property"><em class="xref std std-term">property</em></a>. <a class="reference external" href="http://www.python.org/download/releases/2.2/descrintro/#property">Read more about
properties</a>.</p>
<p>The <a class="reference internal" href="../../ref/models/instances.html"><em>model instance reference</em></a> has a complete list
of <a class="reference internal" href="../../ref/models/instances.html#model-instance-methods"><em>methods automatically given to each model</em></a>.
You can override most of these -- see <a class="reference internal" href="#overriding-predefined-model-methods">overriding predefined model methods</a>,
below -- but there are a couple that you'll almost always want to define:</p>
<dl class="docutils">
<dt><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.__unicode__" title="django.db.models.Model.__unicode__"><tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt></a></dt>
<dd><p class="first">A Python &quot;magic method&quot; that returns a unicode &quot;representation&quot; of any
object. This is what Python and Django will use whenever a model
instance needs to be coerced and displayed as a plain string. Most
notably, this happens when you display an object in an interactive
console or in the admin.</p>
<p class="last">You'll always want to define this method; the default isn't very helpful
at all.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.get_absolute_url" title="django.db.models.Model.get_absolute_url"><tt class="xref py py-meth docutils literal"><span class="pre">get_absolute_url()</span></tt></a></dt>
<dd><p class="first">This tells Django how to calculate the URL for an object. Django uses
this in its admin interface, and any time it needs to figure out a URL
for an object.</p>
<p class="last">Any object that has a URL that uniquely identifies it should define this
method.</p>
</dd>
</dl>
<div class="section" id="s-overriding-predefined-model-methods">
<span id="s-overriding-model-methods"></span><span id="overriding-predefined-model-methods"></span><span id="overriding-model-methods"></span><h3>Overriding predefined model methods<a class="headerlink" href="#overriding-predefined-model-methods" title="Permalink to this headline">¶</a></h3>
<p>There's another set of <a class="reference internal" href="../../ref/models/instances.html#model-instance-methods"><em>model methods</em></a> that
encapsulate a bunch of database behavior that you'll want to customize. In
particular you'll often want to change the way <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> and
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> work.</p>
<p>You're free to override these methods (and any other model method) to alter
behavior.</p>
<p>A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example (see
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for documentation of the parameters it accepts):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <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><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">do_something</span><span class="p">()</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">Blog</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c"># Call the &quot;real&quot; save() method.</span>
        <span class="n">do_something_else</span><span class="p">()</span>
</pre></div>
</div>
<p>You can also prevent saving:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <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><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="s">&quot;Yoko Ono&#39;s blog&quot;</span><span class="p">:</span>
            <span class="k">return</span> <span class="c"># Yoko shall never have her own blog!</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="nb">super</span><span class="p">(</span><span class="n">Blog</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="c"># Call the &quot;real&quot; save() method.</span>
</pre></div>
</div>
<p>It's important to remember to call the superclass method -- that's
that <tt class="docutils literal"><span class="pre">super(Blog,</span> <span class="pre">self).save(*args,</span> <span class="pre">**kwargs)</span></tt> business -- to ensure
that the object still gets saved into the database. If you forget to
call the superclass method, the default behavior won't happen and the
database won't get touched.</p>
<p>It's also important that you pass through the arguments that can be
passed to the model method -- that's what the <tt class="docutils literal"><span class="pre">*args,</span> <span class="pre">**kwargs</span></tt> bit
does. Django will, from time to time, extend the capabilities of
built-in model methods, adding new arguments. If you use <tt class="docutils literal"><span class="pre">*args,</span>
<span class="pre">**kwargs</span></tt> in your method definitions, you are guaranteed that your
code will automatically support those arguments when they are added.</p>
</div>
<div class="section" id="s-executing-custom-sql">
<span id="executing-custom-sql"></span><h3>Executing custom SQL<a class="headerlink" href="#executing-custom-sql" title="Permalink to this headline">¶</a></h3>
<p>Another common pattern is writing custom SQL statements in model methods and
module-level methods. For more details on using raw SQL, see the documentation
on <a class="reference internal" href="sql.html"><em>using raw SQL</em></a>.</p>
</div>
</div>
<div class="section" id="s-model-inheritance">
<span id="s-id5"></span><span id="model-inheritance"></span><span id="id5"></span><h2>Model inheritance<a class="headerlink" href="#model-inheritance" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference internal" href="../../releases/1.0.html"><em>Please, see the release notes</em></a></div>
<p>Model inheritance in Django works almost identically to the way normal
class inheritance works in Python. The only decision you have to make
is whether you want the parent models to be models in their own right
(with their own database tables), or if the parents are just holders
of common information that will only be visible through the child
models.</p>
<p>There are three styles of inheritance that are possible in Django.</p>
<ol class="arabic simple">
<li>Often, you will just want to use the parent class to hold information that
you don't want to have to type out for each child model. This class isn't
going to ever be used in isolation, so <a class="reference internal" href="#abstract-base-classes"><em>Abstract base classes</em></a> are
what you're after.</li>
<li>If you're subclassing an existing model (perhaps something from another
application entirely) and want each model to have its own database table,
<a class="reference internal" href="#multi-table-inheritance"><em>Multi-table inheritance</em></a> is the way to go.</li>
<li>Finally, if you only want to modify the Python-level behaviour of a model,
without changing the models fields in any way, you can use
<a class="reference internal" href="#proxy-models"><em>Proxy models</em></a>.</li>
</ol>
<div class="section" id="s-abstract-base-classes">
<span id="s-id6"></span><span id="abstract-base-classes"></span><span id="id6"></span><h3>Abstract base classes<a class="headerlink" href="#abstract-base-classes" title="Permalink to this headline">¶</a></h3>
<p>Abstract base classes are useful when you want to put some common
information into a number of other models. You write your base class
and put <tt class="docutils literal"><span class="pre">abstract=True</span></tt> in the <a class="reference internal" href="#meta-options"><em>Meta</em></a>
class. This model will then not be used to create any database
table. Instead, when it is used as a base class for other models, its
fields will be added to those of the child class. It is an error to
have fields in the abstract base class with the same name as those in
the child (and Django will raise an exception).</p>
<p>An example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CommonInfo</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">age</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">PositiveIntegerField</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">CommonInfo</span><span class="p">):</span>
    <span class="n">home_group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Student</span></tt> model will have three fields: <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">age</span></tt> and
<tt class="docutils literal"><span class="pre">home_group</span></tt>. The <tt class="docutils literal"><span class="pre">CommonInfo</span></tt> model cannot be used as a normal Django
model, since it is an abstract base class. It does not generate a database
table or have a manager, and cannot be instantiated or saved directly.</p>
<p>For many uses, this type of model inheritance will be exactly what you want.
It provides a way to factor out common information at the Python level, whilst
still only creating one database table per child model at the database level.</p>
<div class="section" id="s-meta-inheritance">
<span id="meta-inheritance"></span><h4><tt class="docutils literal"><span class="pre">Meta</span></tt> inheritance<a class="headerlink" href="#meta-inheritance" title="Permalink to this headline">¶</a></h4>
<p>When an abstract base class is created, Django makes any <a class="reference internal" href="#meta-options"><em>Meta</em></a>
inner class you declared in the base class available as an
attribute. If a child class does not declare its own <a class="reference internal" href="#meta-options"><em>Meta</em></a>
class, it will inherit the parent's <a class="reference internal" href="#meta-options"><em>Meta</em></a>. If the child wants to
extend the parent's <a class="reference internal" href="#meta-options"><em>Meta</em></a> class, it can subclass it. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CommonInfo</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;name&#39;</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">CommonInfo</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="n">CommonInfo</span><span class="o">.</span><span class="n">Meta</span><span class="p">):</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s">&#39;student_info&#39;</span>
</pre></div>
</div>
<p>Django does make one adjustment to the <a class="reference internal" href="#meta-options"><em>Meta</em></a> class of an abstract base
class: before installing the <a class="reference internal" href="#meta-options"><em>Meta</em></a> attribute, it sets <tt class="docutils literal"><span class="pre">abstract=False</span></tt>.
This means that children of abstract base classes don't automatically become
abstract classes themselves. Of course, you can make an abstract base class
that inherits from another abstract base class. You just need to remember to
explicitly set <tt class="docutils literal"><span class="pre">abstract=True</span></tt> each time.</p>
<p>Some attributes won't make sense to include in the <a class="reference internal" href="#meta-options"><em>Meta</em></a> class of an
abstract base class. For example, including <tt class="docutils literal"><span class="pre">db_table</span></tt> would mean that all
the child classes (the ones that don't specify their own <a class="reference internal" href="#meta-options"><em>Meta</em></a>) would use
the same database table, which is almost certainly not what you want.</p>
</div>
<div class="section" id="s-be-careful-with-related-name">
<span id="s-abstract-related-name"></span><span id="be-careful-with-related-name"></span><span id="abstract-related-name"></span><h4>Be careful with <tt class="docutils literal"><span class="pre">related_name</span></tt><a class="headerlink" href="#be-careful-with-related-name" title="Permalink to this headline">¶</a></h4>
<p>If you are using the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> attribute on a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> or
<tt class="docutils literal"><span class="pre">ManyToManyField</span></tt>, you must always specify a <em>unique</em> reverse name for the
field. This would normally cause a problem in abstract base classes, since the
fields on this class are included into each of the child classes, with exactly
the same values for the attributes (including <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>) each time.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.2:</span> <a class="reference internal" href="../../releases/1.2.html"><em>Please, see the release notes</em></a></div>
<p>To work around this problem, when you are using <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> in an
abstract base class (only), part of the name should contain
<tt class="docutils literal"><span class="pre">'%(app_label)s'</span></tt> and <tt class="docutils literal"><span class="pre">'%(class)s'</span></tt>.</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">'%(class)s'</span></tt> is replaced by the lower-cased name of the child class
that the field is used in.</li>
<li><tt class="docutils literal"><span class="pre">'%(app_label)s'</span></tt> is replaced by the lower-cased name of the app the child
class is contained within. Each installed application name must be unique
and the model class names within each app must also be unique, therefore the
resulting name will end up being different.</li>
</ul>
<p>For example, given an app <tt class="docutils literal"><span class="pre">common/models.py</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Base</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">m2m</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">OtherModel</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&quot;</span><span class="si">%(app_label)s</span><span class="s">_</span><span class="si">%(class)s</span><span class="s">_related&quot;</span><span class="p">)</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">ChildA</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">ChildB</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Along with another app <tt class="docutils literal"><span class="pre">rare/models.py</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">common.models</span> <span class="kn">import</span> <span class="n">Base</span>

<span class="k">class</span> <span class="nc">ChildB</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The reverse name of the <tt class="docutils literal"><span class="pre">commmon.ChildA.m2m</span></tt> field will be
<tt class="docutils literal"><span class="pre">common_childa_related</span></tt>, whilst the reverse name of the
<tt class="docutils literal"><span class="pre">common.ChildB.m2m</span></tt> field will be <tt class="docutils literal"><span class="pre">common_childb_related</span></tt>, and finally the
reverse name of the <tt class="docutils literal"><span class="pre">rare.ChildB.m2m</span></tt> field will be <tt class="docutils literal"><span class="pre">rare_childb_related</span></tt>.
It is up to you how you use the <tt class="docutils literal"><span class="pre">'%(class)s'</span></tt> and <tt class="docutils literal"><span class="pre">'%(app_label)s</span></tt> portion
to construct your related name, but if you forget to use it, Django will raise
errors when you validate your models (or run <a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">syncdb</span></tt></a>).</p>
<p>If you don't specify a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>
attribute for a field in an abstract base class, the default reverse name will
be the name of the child class followed by <tt class="docutils literal"><span class="pre">'_set'</span></tt>, just as it normally
would be if you'd declared the field directly on the child class. For example,
in the above code, if the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a>
attribute was omitted, the reverse name for the <tt class="docutils literal"><span class="pre">m2m</span></tt> field would be
<tt class="docutils literal"><span class="pre">childa_set</span></tt> in the <tt class="docutils literal"><span class="pre">ChildA</span></tt> case and <tt class="docutils literal"><span class="pre">childb_set</span></tt> for the <tt class="docutils literal"><span class="pre">ChildB</span></tt>
field.</p>
</div>
</div>
<div class="section" id="s-multi-table-inheritance">
<span id="s-id7"></span><span id="multi-table-inheritance"></span><span id="id7"></span><h3>Multi-table inheritance<a class="headerlink" href="#multi-table-inheritance" title="Permalink to this headline">¶</a></h3>
<p>The second type of model inheritance supported by Django is when each model in
the hierarchy is a model all by itself. Each model corresponds to its own
database table and can be queried and created individually. The inheritance
relationship introduces links between the child model and each of its parents
(via an automatically-created <tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt>).
For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Place</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">address</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">80</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">Place</span><span class="p">):</span>
    <span class="n">serves_hot_dogs</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">()</span>
    <span class="n">serves_pizza</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">()</span>
</pre></div>
</div>
<p>All of the fields of <tt class="docutils literal"><span class="pre">Place</span></tt> will also be available in <tt class="docutils literal"><span class="pre">Restaurant</span></tt>,
although the data will reside in a different database table. So these are both
possible:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Bob&#39;s Cafe&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;Bob&#39;s Cafe&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you have a <tt class="docutils literal"><span class="pre">Place</span></tt> that is also a <tt class="docutils literal"><span class="pre">Restaurant</span></tt>, you can get from the
<tt class="docutils literal"><span class="pre">Place</span></tt> object to the <tt class="docutils literal"><span class="pre">Restaurant</span></tt> object by using the lower-case version
of the model name:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
<span class="go"># If p is a Restaurant object, this will give the child class:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">restaurant</span>
<span class="go">&lt;Restaurant: ...&gt;</span>
</pre></div>
</div>
<p>However, if <tt class="docutils literal"><span class="pre">p</span></tt> in the above example was <em>not</em> a <tt class="docutils literal"><span class="pre">Restaurant</span></tt> (it had been
created directly as a <tt class="docutils literal"><span class="pre">Place</span></tt> object or was the parent of some other class),
referring to <tt class="docutils literal"><span class="pre">p.restaurant</span></tt> would raise a Restaurant.DoesNotExist exception.</p>
<div class="section" id="s-meta-and-multi-table-inheritance">
<span id="meta-and-multi-table-inheritance"></span><h4><tt class="docutils literal"><span class="pre">Meta</span></tt> and multi-table inheritance<a class="headerlink" href="#meta-and-multi-table-inheritance" title="Permalink to this headline">¶</a></h4>
<p>In the multi-table inheritance situation, it doesn't make sense for a child
class to inherit from its parent's <a class="reference internal" href="#meta-options"><em>Meta</em></a> class. All the <a class="reference internal" href="#meta-options"><em>Meta</em></a> options
have already been applied to the parent class and applying them again would
normally only lead to contradictory behavior (this is in contrast with the
abstract base class case, where the base class doesn't exist in its own
right).</p>
<p>So a child model does not have access to its parent's <a class="reference internal" href="#meta-options"><em>Meta</em></a> class. However, there are a few limited cases where the child
inherits behavior from the parent: if the child does not specify an
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">django.db.models.Options.ordering</span></tt></a> attribute or a
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><tt class="xref py py-attr docutils literal"><span class="pre">django.db.models.Options.get_latest_by</span></tt></a> attribute, it will inherit
these from its parent.</p>
<p>If the parent has an ordering and you don't want the child to have any natural
ordering, you can explicitly disable it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ChildModel</span><span class="p">(</span><span class="n">ParentModel</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="c"># Remove parent&#39;s ordering effect</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-inheritance-and-reverse-relations">
<span id="inheritance-and-reverse-relations"></span><h4>Inheritance and reverse relations<a class="headerlink" href="#inheritance-and-reverse-relations" title="Permalink to this headline">¶</a></h4>
<p>Because multi-table inheritance uses an implicit
<tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt> to link the child and
the parent, it's possible to move from the parent down to the child,
as in the above example. However, this uses up the name that is the
default <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> value for
<tt class="xref py py-class docutils literal"><span class="pre">django.db.models.fields.ForeignKey</span></tt> and
<tt class="xref py py-class docutils literal"><span class="pre">django.db.models.fields.ManyToManyField</span></tt> relations.  If you
are putting those types of relations on a subclass of another model,
you <strong>must</strong> specify the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> attribute on each
such field. If you forget, Django will raise an error when you run
<a class="reference internal" href="../../ref/django-admin.html#django-admin-validate"><tt class="xref std std-djadmin docutils literal"><span class="pre">validate</span></tt></a> or <a class="reference internal" href="../../ref/django-admin.html#django-admin-syncdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">syncdb</span></tt></a>.</p>
<p>For example, using the above <tt class="docutils literal"><span class="pre">Place</span></tt> class again, let's create another
subclass with a <tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Supplier</span><span class="p">(</span><span class="n">Place</span><span class="p">):</span>
    <span class="c"># Must specify related_name on all relations.</span>
    <span class="n">customers</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Restaurant</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&#39;provider&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-specifying-the-parent-link-field">
<span id="specifying-the-parent-link-field"></span><h4>Specifying the parent link field<a class="headerlink" href="#specifying-the-parent-link-field" title="Permalink to this headline">¶</a></h4>
<p>As mentioned, Django will automatically create a
<tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt> linking your child
class back any non-abstract parent models. If you want to control the
name of the attribute linking back to the parent, you can create your
own <tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt> and set
<tt class="xref py py-attr docutils literal"><span class="pre">parent_link=True</span></tt>
to indicate that your field is the link back to the parent class.</p>
</div>
</div>
<div class="section" id="s-proxy-models">
<span id="s-id8"></span><span id="proxy-models"></span><span id="id8"></span><h3>Proxy models<a class="headerlink" href="#proxy-models" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.1:</span> <a class="reference internal" href="../../releases/1.1.html"><em>Please, see the release notes</em></a></div>
<p>When using <a class="reference internal" href="#multi-table-inheritance"><em>multi-table inheritance</em></a>, a new
database table is created for each subclass of a model. This is usually the
desired behavior, since the subclass needs a place to store any additional
data fields that are not present on the base class. Sometimes, however, you
only want to change the Python behavior of a model -- perhaps to change the
default manager, or add a new method.</p>
<p>This is what proxy model inheritance is for: creating a <em>proxy</em> for the
original model. You can create, delete and update instances of the proxy model
and all the data will be saved as if you were using the original (non-proxied)
model. The difference is that you can change things like the default model
ordering or the default manager in the proxy, without having to alter the
original.</p>
<p>Proxy models are declared like normal models. You tell Django that it's a
proxy model by setting the <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.proxy" title="django.db.models.Options.proxy"><tt class="xref py py-attr docutils literal"><span class="pre">proxy</span></tt></a> attribute of
the <tt class="docutils literal"><span class="pre">Meta</span></tt> class to <tt class="xref docutils literal"><span class="pre">True</span></tt>.</p>
<p>For example, suppose you want to add a method to the standard <tt class="docutils literal"><span class="pre">User</span></tt> model
that will be used in your templates. You can do it like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span>

<span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">MyUser</span></tt> class operates on the same database table as its parent
<tt class="docutils literal"><span class="pre">User</span></tt> class. In particular, any new instances of <tt class="docutils literal"><span class="pre">User</span></tt> will also be
accessible through <tt class="docutils literal"><span class="pre">MyUser</span></tt>, and vice-versa:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">&quot;foobar&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MyUser</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">&quot;foobar&quot;</span><span class="p">)</span>
<span class="go">&lt;MyUser: foobar&gt;</span>
</pre></div>
</div>
<p>You could also use a proxy model to define a different default ordering on a
model. The standard <tt class="docutils literal"><span class="pre">User</span></tt> model has no ordering defined on it
(intentionally; sorting is expensive and we don't want to do it all the time
when we fetch users). You might want to regularly order by the <tt class="docutils literal"><span class="pre">username</span></tt>
attribute when you use the proxy. This is easy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">OrderedUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;username&quot;</span><span class="p">]</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>Now normal <tt class="docutils literal"><span class="pre">User</span></tt> queries will be unorderd and <tt class="docutils literal"><span class="pre">OrderedUser</span></tt> queries will
be ordered by <tt class="docutils literal"><span class="pre">username</span></tt>.</p>
<div class="section" id="s-querysets-still-return-the-model-that-was-requested">
<span id="querysets-still-return-the-model-that-was-requested"></span><h4>QuerySets still return the model that was requested<a class="headerlink" href="#querysets-still-return-the-model-that-was-requested" title="Permalink to this headline">¶</a></h4>
<p>There is no way to have Django return, say, a <tt class="docutils literal"><span class="pre">MyUser</span></tt> object whenever you
query for <tt class="docutils literal"><span class="pre">User</span></tt> objects. A queryset for <tt class="docutils literal"><span class="pre">User</span></tt> objects will return those
types of objects. The whole point of proxy objects is that code relying on the
original <tt class="docutils literal"><span class="pre">User</span></tt> will use those and your own code can use the extensions you
included (that no other code is relying on anyway). It is not a way to replace
the <tt class="docutils literal"><span class="pre">User</span></tt> (or any other) model everywhere with something of your own
creation.</p>
</div>
<div class="section" id="s-base-class-restrictions">
<span id="base-class-restrictions"></span><h4>Base class restrictions<a class="headerlink" href="#base-class-restrictions" title="Permalink to this headline">¶</a></h4>
<p>A proxy model must inherit from exactly one non-abstract model class. You
can't inherit from multiple non-abstract models as the proxy model doesn't
provide any connection between the rows in the different database tables. A
proxy model can inherit from any number of abstract model classes, providing
they do <em>not</em> define any model fields.</p>
<p>Proxy models inherit any <tt class="docutils literal"><span class="pre">Meta</span></tt> options that they don't define from their
non-abstract model parent (the model they are proxying for).</p>
</div>
<div class="section" id="s-proxy-model-managers">
<span id="proxy-model-managers"></span><h4>Proxy model managers<a class="headerlink" href="#proxy-model-managers" title="Permalink to this headline">¶</a></h4>
<p>If you don't specify any model managers on a proxy model, it inherits the
managers from its model parents. If you define a manager on the proxy model,
it will become the default, although any managers defined on the parent
classes will still be available.</p>
<p>Continuing our example from above, you could change the default manager used
when you query the <tt class="docutils literal"><span class="pre">User</span></tt> model like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">NewManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="o">...</span>

<span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">NewManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>If you wanted to add a new manager to the Proxy, without replacing the
existing default, you can use the techniques described in the <a class="reference internal" href="managers.html#custom-managers-and-inheritance"><em>custom
manager</em></a> documentation: create a base class
containing the new managers and inherit that after the primary base class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Create an abstract class for the new manager.</span>
<span class="k">class</span> <span class="nc">ExtraManagers</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">secondary</span> <span class="o">=</span> <span class="n">NewManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">ExtraManagers</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">proxy</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>You probably won't need to do this very often, but, when you do, it's
possible.</p>
</div>
<div class="section" id="s-differences-between-proxy-inheritance-and-unmanaged-models">
<span id="s-proxy-vs-unmanaged-models"></span><span id="differences-between-proxy-inheritance-and-unmanaged-models"></span><span id="proxy-vs-unmanaged-models"></span><h4>Differences between proxy inheritance and  unmanaged models<a class="headerlink" href="#differences-between-proxy-inheritance-and-unmanaged-models" title="Permalink to this headline">¶</a></h4>
<p>Proxy model inheritance might look fairly similar to creating an unmanaged
model, using the <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.managed" title="django.db.models.Options.managed"><tt class="xref py py-attr docutils literal"><span class="pre">managed</span></tt></a> attribute on a
model's <tt class="docutils literal"><span class="pre">Meta</span></tt> class. The two alternatives are not quite the same and it's
worth considering which one you should use.</p>
<p>One difference is that you can (and, in fact, must unless you want an empty
model) specify model fields on models with <tt class="docutils literal"><span class="pre">Meta.managed=False</span></tt>. You could,
with careful setting of <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-attr docutils literal"><span class="pre">Meta.db_table</span></tt></a> create an unmanaged model that shadowed
an existing model and add Python methods to it. However, that would be very
repetitive and fragile as you need to keep both copies synchronized if you
make any changes.</p>
<p>The other difference that is more important for proxy models, is how model
managers are handled. Proxy models are intended to behave exactly like the
model they are proxying for. So they inherit the parent model's managers,
including the default manager. In the normal multi-table model inheritance
case, children do not inherit managers from their parents as the custom
managers aren't always appropriate when extra fields are involved. The
<a class="reference internal" href="managers.html#custom-managers-and-inheritance"><em>manager documentation</em></a> has more
details about this latter case.</p>
<p>When these two features were implemented, attempts were made to squash them
into a single option. It turned out that interactions with inheritance, in
general, and managers, in particular, made the API very complicated and
potentially difficult to understand and use. It turned out that two options
were needed in any case, so the current separation arose.</p>
<p>So, the general rules are:</p>
<ol class="arabic simple">
<li>If you are mirroring an existing model or database table and don't want
all the original database table columns, use <tt class="docutils literal"><span class="pre">Meta.managed=False</span></tt>.
That option is normally useful for modeling database views and tables
not under the control of Django.</li>
<li>If you are wanting to change the Python-only behavior of a model, but
keep all the same fields as in the original, use <tt class="docutils literal"><span class="pre">Meta.proxy=True</span></tt>.
This sets things up so that the proxy model is an exact copy of the
storage structure of the original model when data is saved.</li>
</ol>
</div>
</div>
<div class="section" id="s-multiple-inheritance">
<span id="multiple-inheritance"></span><h3>Multiple inheritance<a class="headerlink" href="#multiple-inheritance" title="Permalink to this headline">¶</a></h3>
<p>Just as with Python's subclassing, it's possible for a Django model to inherit
from multiple parent models. Keep in mind that normal Python name resolution
rules apply. The first base class that a particular name (e.g. <a class="reference internal" href="#meta-options"><em>Meta</em></a>) appears in will be the one that is used; for example, this
means that if multiple parents contain a <a class="reference internal" href="#meta-options"><em>Meta</em></a> class,
only the first one is going to be used, and all others will be ignored.</p>
<p>Generally, you won't need to inherit from multiple parents. The main use-case
where this is useful is for &quot;mix-in&quot; classes: adding a particular extra
field or method to every class that inherits the mix-in. Try to keep your
inheritance hierarchies as simple and straightforward as possible so that you
won't have to struggle to work out where a particular piece of information is
coming from.</p>
</div>
<div class="section" id="s-field-name-hiding-is-not-permitted">
<span id="field-name-hiding-is-not-permitted"></span><h3>Field name &quot;hiding&quot; is not permitted<a class="headerlink" href="#field-name-hiding-is-not-permitted" title="Permalink to this headline">¶</a></h3>
<p>In normal Python class inheritance, it is permissible for a child class to
override any attribute from the parent class. In Django, this is not permitted
for attributes that are <tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt> instances (at
least, not at the moment). If a base class has a field called <tt class="docutils literal"><span class="pre">author</span></tt>, you
cannot create another model field called <tt class="docutils literal"><span class="pre">author</span></tt> in any class that inherits
from that base class.</p>
<p>Overriding fields in a parent model leads to difficulties in areas such as
initialising new instances (specifying which field is being intialised in
<tt class="docutils literal"><span class="pre">Model.__init__</span></tt>) and serialization. These are features which normal Python
class inheritance doesn't have to deal with in quite the same way, so the
difference between Django model inheritance and Python class inheritance isn't
merely arbitrary.</p>
<p>This restriction only applies to attributes which are
<tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt> instances. Normal Python attributes
can be overridden if you wish. It also only applies to the name of the
attribute as Python sees it: if you are manually specifying the database
column name, you can have the same column name appearing in both a child and
an ancestor model for multi-table inheritance (they are columns in two
different database tables).</p>
<p>Django will raise a <tt class="docutils literal"><span class="pre">FieldError</span></tt> exception if you override any model field
in any ancestor model.</p>
</div>
</div>
</div>


          </div>         
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Models</a><ul>
<li><a class="reference internal" href="#quick-example">Quick example</a></li>
<li><a class="reference internal" href="#using-models">Using models</a></li>
<li><a class="reference internal" href="#fields">Fields</a><ul>
<li><a class="reference internal" href="#field-types">Field types</a></li>
<li><a class="reference internal" href="#field-options">Field options</a></li>
<li><a class="reference internal" href="#automatic-primary-key-fields">Automatic primary key fields</a></li>
<li><a class="reference internal" href="#verbose-field-names">Verbose field names</a></li>
<li><a class="reference internal" href="#relationships">Relationships</a><ul>
<li><a class="reference internal" href="#many-to-one-relationships">Many-to-one relationships</a></li>
<li><a class="reference internal" href="#many-to-many-relationships">Many-to-many relationships</a></li>
<li><a class="reference internal" href="#extra-fields-on-many-to-many-relationships">Extra fields on many-to-many relationships</a></li>
<li><a class="reference internal" href="#one-to-one-relationships">One-to-one relationships</a></li>
</ul>
</li>
<li><a class="reference internal" href="#models-across-files">Models across files</a></li>
<li><a class="reference internal" href="#field-name-restrictions">Field name restrictions</a></li>
<li><a class="reference internal" href="#custom-field-types">Custom field types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#meta-options">Meta options</a></li>
<li><a class="reference internal" href="#model-methods">Model methods</a><ul>
<li><a class="reference internal" href="#overriding-predefined-model-methods">Overriding predefined model methods</a></li>
<li><a class="reference internal" href="#executing-custom-sql">Executing custom SQL</a></li>
</ul>
</li>
<li><a class="reference internal" href="#model-inheritance">Model inheritance</a><ul>
<li><a class="reference internal" href="#abstract-base-classes">Abstract base classes</a><ul>
<li><a class="reference internal" href="#meta-inheritance"><tt class="docutils literal"><span class="pre">Meta</span></tt> inheritance</a></li>
<li><a class="reference internal" href="#be-careful-with-related-name">Be careful with <tt class="docutils literal"><span class="pre">related_name</span></tt></a></li>
</ul>
</li>
<li><a class="reference internal" href="#multi-table-inheritance">Multi-table inheritance</a><ul>
<li><a class="reference internal" href="#meta-and-multi-table-inheritance"><tt class="docutils literal"><span class="pre">Meta</span></tt> and multi-table inheritance</a></li>
<li><a class="reference internal" href="#inheritance-and-reverse-relations">Inheritance and reverse relations</a></li>
<li><a class="reference internal" href="#specifying-the-parent-link-field">Specifying the parent link field</a></li>
</ul>
</li>
<li><a class="reference internal" href="#proxy-models">Proxy models</a><ul>
<li><a class="reference internal" href="#querysets-still-return-the-model-that-was-requested">QuerySets still return the model that was requested</a></li>
<li><a class="reference internal" href="#base-class-restrictions">Base class restrictions</a></li>
<li><a class="reference internal" href="#proxy-model-managers">Proxy model managers</a></li>
<li><a class="reference internal" href="#differences-between-proxy-inheritance-and-unmanaged-models">Differences between proxy inheritance and  unmanaged models</a></li>
</ul>
</li>
<li><a class="reference internal" href="#multiple-inheritance">Multiple inheritance</a></li>
<li><a class="reference internal" href="#field-name-hiding-is-not-permitted">Field name &#8220;hiding&#8221; is not permitted</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="index.html">Models and databases</a></li>
    
    
      <li>Next: <a href="queries.html">Making queries</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django v1.2 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Models</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>  

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/db/models.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Oct 20, 2010</p>
          </div> 
        
      
    </div>
    
    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="Models and databases">previous</a> 
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="queries.html" title="Making queries">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>