<!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>Model instance reference — Django 1.4.20 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.4.20', 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 1.4.20 documentation" href="../../index.html" /> <link rel="up" title="Models" href="index.html" /> <link rel="next" title="QuerySet API reference" href="querysets.html" /> <link rel="prev" title="Model Meta options" href="options.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 = "../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 1.4.20 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"> « <a href="options.html" title="Model <tt class="docutils literal"><span class="pre">Meta</span></tt> options">previous</a> | <a href="../index.html" title="API Reference" accesskey="U">up</a> | <a href="querysets.html" title="QuerySet API reference">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="ref-models-instances"> <div class="section" id="s-model-instance-reference"> <span id="model-instance-reference"></span><h1>Model instance reference<a class="headerlink" href="#model-instance-reference" title="Permalink to this headline">¶</a></h1> <p>This document describes the details of the <tt class="docutils literal"><span class="pre">Model</span></tt> API. It builds on the material presented in the <a class="reference internal" href="../../topics/db/models.html"><em>model</em></a> and <a class="reference internal" href="../../topics/db/queries.html"><em>database query</em></a> guides, so you’ll probably want to read and understand those documents before reading this one.</p> <p>Throughout this reference we’ll use the <a class="reference internal" href="../../topics/db/queries.html#queryset-model-example"><em>example Weblog models</em></a> presented in the <a class="reference internal" href="../../topics/db/queries.html"><em>database query guide</em></a>.</p> <div class="section" id="s-creating-objects"> <span id="creating-objects"></span><h2>Creating objects<a class="headerlink" href="#creating-objects" title="Permalink to this headline">¶</a></h2> <p>To create a new instance of a model, just instantiate it like any other Python class:</p> <dl class="class"> <dt id="django.db.models.Model"> <em class="property">class </em><tt class="descname">Model</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.Model" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to <a class="reference internal" href="#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>.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>You may be tempted to customize the model by overriding the <tt class="docutils literal"><span class="pre">__init__</span></tt> method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding <tt class="docutils literal"><span class="pre">__init__</span></tt>, try using one of these approaches:</p> <ol class="last arabic"> <li><p class="first">Add a classmethod on the model class:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Book</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">title</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="nd">@classmethod</span> <span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">title</span><span class="p">):</span> <span class="n">book</span> <span class="o">=</span> <span class="n">cls</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="n">title</span><span class="p">)</span> <span class="c"># do something with the book</span> <span class="k">return</span> <span class="n">book</span> <span class="n">book</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="s">"Pride and Prejudice"</span><span class="p">)</span> </pre></div> </div> </li> <li><p class="first">Add a method on a custom manager (usually preferred):</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">BookManager</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="k">def</span> <span class="nf">create_book</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">title</span><span class="p">):</span> <span class="n">book</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="n">title</span><span class="p">)</span> <span class="c"># do something with the book</span> <span class="k">return</span> <span class="n">book</span> <span class="k">class</span> <span class="nc">Book</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">title</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">objects</span> <span class="o">=</span> <span class="n">BookManager</span><span class="p">()</span> <span class="n">book</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create_book</span><span class="p">(</span><span class="s">"Pride and Prejudice"</span><span class="p">)</span> </pre></div> </div> </li> </ol> </div> </div> <div class="section" id="s-validating-objects"> <span id="s-id1"></span><span id="validating-objects"></span><span id="id1"></span><h2>Validating objects<a class="headerlink" href="#validating-objects" title="Permalink to this headline">¶</a></h2> <div class="versionadded"> <span class="title">New in Django 1.2:</span> <a class="reference internal" href="../../releases/1.2.html"><em>Please see the release notes</em></a></div> <p>There are three steps involved in validating a model:</p> <ol class="arabic simple"> <li>Validate the model fields</li> <li>Validate the model as a whole</li> <li>Validate the field uniqueness</li> </ol> <p>All three steps are performed when you call a model’s <a class="reference internal" href="#django.db.models.Model.full_clean" title="django.db.models.Model.full_clean"><tt class="xref py py-meth docutils literal"><span class="pre">full_clean()</span></tt></a> method.</p> <p>When you use a <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><tt class="xref py py-class docutils literal"><span class="pre">ModelForm</span></tt></a>, the call to <a class="reference internal" href="../forms/api.html#django.forms.Form.is_valid" title="django.forms.Form.is_valid"><tt class="xref py py-meth docutils literal"><span class="pre">is_valid()</span></tt></a> will perform these validation steps for all the fields that are included on the form. See the <a class="reference internal" href="../../topics/forms/modelforms.html"><em>ModelForm documentation</em></a> for more information. You should only need to call a model’s <a class="reference internal" href="#django.db.models.Model.full_clean" title="django.db.models.Model.full_clean"><tt class="xref py py-meth docutils literal"><span class="pre">full_clean()</span></tt></a> method if you plan to handle validation errors yourself, or if you have excluded fields from the <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><tt class="xref py py-class docutils literal"><span class="pre">ModelForm</span></tt></a> that require validation.</p> <dl class="method"> <dt id="django.db.models.Model.full_clean"> <tt class="descclassname">Model.</tt><tt class="descname">full_clean</tt>(<em>exclude=None</em>)<a class="headerlink" href="#django.db.models.Model.full_clean" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method calls <a class="reference internal" href="#django.db.models.Model.clean_fields" title="django.db.models.Model.clean_fields"><tt class="xref py py-meth docutils literal"><span class="pre">Model.clean_fields()</span></tt></a>, <a class="reference internal" href="#django.db.models.Model.clean" title="django.db.models.Model.clean"><tt class="xref py py-meth docutils literal"><span class="pre">Model.clean()</span></tt></a>, and <a class="reference internal" href="#django.db.models.Model.validate_unique" title="django.db.models.Model.validate_unique"><tt class="xref py py-meth docutils literal"><span class="pre">Model.validate_unique()</span></tt></a>, in that order and raises a <a class="reference internal" href="../exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><tt class="xref py py-exc docutils literal"><span class="pre">ValidationError</span></tt></a> that has a <tt class="docutils literal"><span class="pre">message_dict</span></tt> attribute containing errors from all three stages.</p> <p>The optional <tt class="docutils literal"><span class="pre">exclude</span></tt> argument can be used to provide a list of field names that can be excluded from validation and cleaning. <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><tt class="xref py py-class docutils literal"><span class="pre">ModelForm</span></tt></a> uses this argument to exclude fields that aren’t present on your form from being validated since any errors raised could not be corrected by the user.</p> <p>Note that <tt class="docutils literal"><span class="pre">full_clean()</span></tt> will <em>not</em> be called automatically when you call your model’s <a class="reference internal" href="#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> method, nor as a result of <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><tt class="xref py py-class docutils literal"><span class="pre">ModelForm</span></tt></a> validation. You’ll need to call it manually when you want to run one-step model validation for your own manually created models.</p> <p>Example:</p> <div class="highlight-python"><pre>try: article.full_clean() except ValidationError, e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programatically.</pre> </div> <p>The first step <tt class="docutils literal"><span class="pre">full_clean()</span></tt> performs is to clean each individual field.</p> <dl class="method"> <dt id="django.db.models.Model.clean_fields"> <tt class="descclassname">Model.</tt><tt class="descname">clean_fields</tt>(<em>exclude=None</em>)<a class="headerlink" href="#django.db.models.Model.clean_fields" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method will validate all fields on your model. The optional <tt class="docutils literal"><span class="pre">exclude</span></tt> argument lets you provide a list of field names to exclude from validation. It will raise a <a class="reference internal" href="../exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><tt class="xref py py-exc docutils literal"><span class="pre">ValidationError</span></tt></a> if any fields fail validation.</p> <p>The second step <tt class="docutils literal"><span class="pre">full_clean()</span></tt> performs is to call <a class="reference internal" href="#django.db.models.Model.clean" title="django.db.models.Model.clean"><tt class="xref py py-meth docutils literal"><span class="pre">Model.clean()</span></tt></a>. This method should be overridden to perform custom validation on your model.</p> <dl class="method"> <dt id="django.db.models.Model.clean"> <tt class="descclassname">Model.</tt><tt class="descname">clean</tt>()<a class="headerlink" href="#django.db.models.Model.clean" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">clean</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="kn">import</span> <span class="n">ValidationError</span> <span class="c"># Don't allow draft entries to have a pub_date.</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">status</span> <span class="o">==</span> <span class="s">'draft'</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="s">'Draft entries may not have a publication date.'</span><span class="p">)</span> <span class="c"># Set the pub_date for published items if it hasn't been set already.</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">status</span> <span class="o">==</span> <span class="s">'published'</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> </pre></div> </div> <p>Any <a class="reference internal" href="../exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><tt class="xref py py-exc docutils literal"><span class="pre">ValidationError</span></tt></a> exceptions raised by <tt class="docutils literal"><span class="pre">Model.clean()</span></tt> will be stored in a special key error dictionary key, <tt class="docutils literal"><span class="pre">NON_FIELD_ERRORS</span></tt>, that is used for errors that are tied to the entire model instead of to a specific field:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="kn">import</span> <span class="n">ValidationError</span><span class="p">,</span> <span class="n">NON_FIELD_ERRORS</span> <span class="k">try</span><span class="p">:</span> <span class="n">article</span><span class="o">.</span><span class="n">full_clean</span><span class="p">()</span> <span class="k">except</span> <span class="n">ValidationError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span> <span class="n">non_field_errors</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">message_dict</span><span class="p">[</span><span class="n">NON_FIELD_ERRORS</span><span class="p">]</span> </pre></div> </div> <p>Finally, <tt class="docutils literal"><span class="pre">full_clean()</span></tt> will check any unique constraints on your model.</p> <dl class="method"> <dt id="django.db.models.Model.validate_unique"> <tt class="descclassname">Model.</tt><tt class="descname">validate_unique</tt>(<em>exclude=None</em>)<a class="headerlink" href="#django.db.models.Model.validate_unique" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method is similar to <a class="reference internal" href="#django.db.models.Model.clean_fields" title="django.db.models.Model.clean_fields"><tt class="xref py py-meth docutils literal"><span class="pre">clean_fields()</span></tt></a>, but validates all uniqueness constraints on your model instead of individual field values. The optional <tt class="docutils literal"><span class="pre">exclude</span></tt> argument allows you to provide a list of field names to exclude from validation. It will raise a <a class="reference internal" href="../exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><tt class="xref py py-exc docutils literal"><span class="pre">ValidationError</span></tt></a> if any fields fail validation.</p> <p>Note that if you provide an <tt class="docutils literal"><span class="pre">exclude</span></tt> argument to <tt class="docutils literal"><span class="pre">validate_unique()</span></tt>, any <a class="reference internal" href="options.html#django.db.models.Options.unique_together" title="django.db.models.Options.unique_together"><tt class="xref py py-attr docutils literal"><span class="pre">unique_together</span></tt></a> constraint involving one of the fields you provided will not be checked.</p> </div> <div class="section" id="s-saving-objects"> <span id="saving-objects"></span><h2>Saving objects<a class="headerlink" href="#saving-objects" title="Permalink to this headline">¶</a></h2> <p>To save an object back to the database, call <tt class="docutils literal"><span class="pre">save()</span></tt>:</p> <dl class="method"> <dt id="django.db.models.Model.save"> <tt class="descclassname">Model.</tt><tt class="descname">save</tt>(<span class="optional">[</span><em>force_insert=False</em>, <em>force_update=False</em>, <em>using=DEFAULT_DB_ALIAS</em><span class="optional">]</span>)<a class="headerlink" href="#django.db.models.Model.save" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.2:</span> The <tt class="docutils literal"><span class="pre">using</span></tt> argument was added.</div> <p>If you want customized saving behavior, you can override this <tt class="docutils literal"><span class="pre">save()</span></tt> method. See <a class="reference internal" href="../../topics/db/models.html#overriding-model-methods"><em>Overriding predefined model methods</em></a> for more details.</p> <p>The model save process also has some subtleties; see the sections below.</p> <div class="section" id="s-auto-incrementing-primary-keys"> <span id="auto-incrementing-primary-keys"></span><h3>Auto-incrementing primary keys<a class="headerlink" href="#auto-incrementing-primary-keys" title="Permalink to this headline">¶</a></h3> <p>If a model has an <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> — an auto-incrementing primary key — then that auto-incremented value will be calculated and saved as an attribute on your object the first time you call <tt class="docutils literal"><span class="pre">save()</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">b2</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">'Cheddar Talk'</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s">'Thoughts on cheese.'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">b2</span><span class="o">.</span><span class="n">id</span> <span class="c"># Returns None, because b doesn't have an ID yet.</span> <span class="gp">>>> </span><span class="n">b2</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">b2</span><span class="o">.</span><span class="n">id</span> <span class="c"># Returns the ID of your new object.</span> </pre></div> </div> <p>There’s no way to tell what the value of an ID will be before you call <tt class="docutils literal"><span class="pre">save()</span></tt>, because that value is calculated by your database, not by Django.</p> <p>For convenience, each model has an <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> named <tt class="docutils literal"><span class="pre">id</span></tt> by default unless you explicitly specify <tt class="docutils literal"><span class="pre">primary_key=True</span></tt> on a field in your model. See the documentation for <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> for more details.</p> <div class="section" id="s-the-pk-property"> <span id="the-pk-property"></span><h4>The <tt class="docutils literal"><span class="pre">pk</span></tt> property<a class="headerlink" href="#the-pk-property" title="Permalink to this headline">¶</a></h4> <dl class="attribute"> <dt id="django.db.models.Model.pk"> <tt class="descclassname">Model.</tt><tt class="descname">pk</tt><a class="headerlink" href="#django.db.models.Model.pk" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Regardless of whether you define a primary key field yourself, or let Django supply one for you, each model will have a property called <tt class="docutils literal"><span class="pre">pk</span></tt>. It behaves like a normal attribute on the model, but is actually an alias for whichever attribute is the primary key field for the model. You can read and set this value, just as you would for any other attribute, and it will update the correct field in the model.</p> </div> <div class="section" id="s-explicitly-specifying-auto-primary-key-values"> <span id="explicitly-specifying-auto-primary-key-values"></span><h4>Explicitly specifying auto-primary-key values<a class="headerlink" href="#explicitly-specifying-auto-primary-key-values" title="Permalink to this headline">¶</a></h4> <p>If a model has an <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> but you want to define a new object’s ID explicitly when saving, just define it explicitly before saving, rather than relying on the auto-assignment of the ID:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">b3</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'Cheddar Talk'</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s">'Thoughts on cheese.'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">b3</span><span class="o">.</span><span class="n">id</span> <span class="c"># Returns 3.</span> <span class="gp">>>> </span><span class="n">b3</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">b3</span><span class="o">.</span><span class="n">id</span> <span class="c"># Returns 3.</span> </pre></div> </div> <p>If you assign auto-primary-key values manually, make sure not to use an already-existing primary-key value! If you create a new object with an explicit primary-key value that already exists in the database, Django will assume you’re changing the existing record rather than creating a new one.</p> <p>Given the above <tt class="docutils literal"><span class="pre">'Cheddar</span> <span class="pre">Talk'</span></tt> blog example, this example would override the previous record in the database:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">b4</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'Not Cheddar'</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s">'Anything but cheese.'</span><span class="p">)</span> <span class="n">b4</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Overrides the previous blog with ID=3!</span> </pre></div> </div> <p>See <a class="reference internal" href="#how-django-knows-to-update-vs-insert">How Django knows to UPDATE vs. INSERT</a>, below, for the reason this happens.</p> <p>Explicitly specifying auto-primary-key values is mostly useful for bulk-saving objects, when you’re confident you won’t have primary-key collision.</p> </div> </div> <div class="section" id="s-what-happens-when-you-save"> <span id="what-happens-when-you-save"></span><h3>What happens when you save?<a class="headerlink" href="#what-happens-when-you-save" title="Permalink to this headline">¶</a></h3> <p>When you save an object, Django performs the following steps:</p> <ol class="arabic"> <li><p class="first"><strong>Emit a pre-save signal.</strong> The <a class="reference internal" href="../signals.html"><em>signal</em></a> <a class="reference internal" href="../signals.html#django.db.models.signals.pre_save" title="django.db.models.signals.pre_save"><tt class="xref py py-attr docutils literal"><span class="pre">django.db.models.signals.pre_save</span></tt></a> is sent, allowing any functions listening for that signal to take some customized action.</p> </li> <li><p class="first"><strong>Pre-process the data.</strong> Each field on the object is asked to perform any automated data modification that the field may need to perform.</p> <p>Most fields do <em>no</em> pre-processing — the field data is kept as-is. Pre-processing is only used on fields that have special behavior. For example, if your model has a <a class="reference internal" href="fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">DateField</span></tt></a> with <tt class="docutils literal"><span class="pre">auto_now=True</span></tt>, the pre-save phase will alter the data in the object to ensure that the date field contains the current date stamp. (Our documentation doesn’t yet include a list of all the fields with this “special behavior.”)</p> </li> <li><p class="first"><strong>Prepare the data for the database.</strong> Each field is asked to provide its current value in a data type that can be written to the database.</p> <p>Most fields require <em>no</em> data preparation. Simple data types, such as integers and strings, are ‘ready to write’ as a Python object. However, more complex data types often require some modification.</p> <p>For example, <a class="reference internal" href="fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">DateField</span></tt></a> fields use a Python <tt class="docutils literal"><span class="pre">datetime</span></tt> object to store data. Databases don’t store <tt class="docutils literal"><span class="pre">datetime</span></tt> objects, so the field value must be converted into an ISO-compliant date string for insertion into the database.</p> </li> <li><p class="first"><strong>Insert the data into the database.</strong> The pre-processed, prepared data is then composed into an SQL statement for insertion into the database.</p> </li> <li><p class="first"><strong>Emit a post-save signal.</strong> The signal <a class="reference internal" href="../signals.html#django.db.models.signals.post_save" title="django.db.models.signals.post_save"><tt class="xref py py-attr docutils literal"><span class="pre">django.db.models.signals.post_save</span></tt></a> is sent, allowing any functions listening for that signal to take some customized action.</p> </li> </ol> </div> <div class="section" id="s-how-django-knows-to-update-vs-insert"> <span id="how-django-knows-to-update-vs-insert"></span><h3>How Django knows to UPDATE vs. INSERT<a class="headerlink" href="#how-django-knows-to-update-vs-insert" title="Permalink to this headline">¶</a></h3> <p>You may have noticed Django database objects use the same <tt class="docutils literal"><span class="pre">save()</span></tt> method for creating and changing objects. Django abstracts the need to use <tt class="docutils literal"><span class="pre">INSERT</span></tt> or <tt class="docutils literal"><span class="pre">UPDATE</span></tt> SQL statements. Specifically, when you call <tt class="docutils literal"><span class="pre">save()</span></tt>, Django follows this algorithm:</p> <ul class="simple"> <li>If the object’s primary key attribute is set to a value that evaluates to <tt class="docutils literal"><span class="pre">True</span></tt> (i.e., a value other than <tt class="docutils literal"><span class="pre">None</span></tt> or the empty string), Django executes a <tt class="docutils literal"><span class="pre">SELECT</span></tt> query to determine whether a record with the given primary key already exists.</li> <li>If the record with the given primary key does already exist, Django executes an <tt class="docutils literal"><span class="pre">UPDATE</span></tt> query.</li> <li>If the object’s primary key attribute is <em>not</em> set, or if it’s set but a record doesn’t exist, Django executes an <tt class="docutils literal"><span class="pre">INSERT</span></tt>.</li> </ul> <p>The one gotcha here is that you should be careful not to specify a primary-key value explicitly when saving new objects, if you cannot guarantee the primary-key value is unused. For more on this nuance, see <a class="reference internal" href="#explicitly-specifying-auto-primary-key-values">Explicitly specifying auto-primary-key values</a> above and <a class="reference internal" href="#forcing-an-insert-or-update">Forcing an INSERT or UPDATE</a> below.</p> <div class="section" id="s-forcing-an-insert-or-update"> <span id="s-ref-models-force-insert"></span><span id="forcing-an-insert-or-update"></span><span id="ref-models-force-insert"></span><h4>Forcing an INSERT or UPDATE<a class="headerlink" href="#forcing-an-insert-or-update" title="Permalink to this headline">¶</a></h4> <p>In some rare circumstances, it’s necessary to be able to force the <a class="reference internal" href="#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> method to perform an SQL <tt class="docutils literal"><span class="pre">INSERT</span></tt> and not fall back to doing an <tt class="docutils literal"><span class="pre">UPDATE</span></tt>. Or vice-versa: update, if possible, but not insert a new row. In these cases you can pass the <tt class="docutils literal"><span class="pre">force_insert=True</span></tt> or <tt class="docutils literal"><span class="pre">force_update=True</span></tt> parameters to the <a class="reference internal" href="#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> method. Obviously, passing both parameters is an error: you cannot both insert <em>and</em> update at the same time!</p> <p>It should be very rare that you’ll need to use these parameters. Django will almost always do the right thing and trying to override that will lead to errors that are difficult to track down. This feature is for advanced use only.</p> </div> </div> <div class="section" id="s-updating-attributes-based-on-existing-fields"> <span id="updating-attributes-based-on-existing-fields"></span><h3>Updating attributes based on existing fields<a class="headerlink" href="#updating-attributes-based-on-existing-fields" title="Permalink to this headline">¶</a></h3> <p>Sometimes you’ll need to perform a simple arithmetic task on a field, such as incrementing or decrementing the current value. The obvious way to achieve this is to do something like:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">product</span> <span class="o">=</span> <span class="n">Product</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">name</span><span class="o">=</span><span class="s">'Venezuelan Beaver Cheese'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">product</span><span class="o">.</span><span class="n">number_sold</span> <span class="o">+=</span> <span class="mi">1</span> <span class="gp">>>> </span><span class="n">product</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> <p>If the old <tt class="docutils literal"><span class="pre">number_sold</span></tt> value retrieved from the database was 10, then the value of 11 will be written back to the database.</p> <p>This sequence has a standard update problem in that it contains a race condition. If another thread of execution has already saved an updated value after the current thread retrieved the old value, the current thread will only save the old value plus one, rather than the new (current) value plus one.</p> <p>The process can be made robust and slightly faster by expressing the update relative to the original field value, rather than as an explicit assignment of a new value. Django provides <a class="reference internal" href="../../topics/db/queries.html#query-expressions"><em>F() expressions</em></a> for performing this kind of relative update. Using <tt class="docutils literal"><span class="pre">F()</span></tt> expressions, the previous example is expressed as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">F</span> <span class="gp">>>> </span><span class="n">product</span> <span class="o">=</span> <span class="n">Product</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">name</span><span class="o">=</span><span class="s">'Venezuelan Beaver Cheese'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">product</span><span class="o">.</span><span class="n">number_sold</span> <span class="o">=</span> <span class="n">F</span><span class="p">(</span><span class="s">'number_sold'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> <span class="gp">>>> </span><span class="n">product</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> <p>This approach doesn’t use the initial value from the database. Instead, it makes the database do the update based on whatever value is current at the time that the <a class="reference internal" href="#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> is executed.</p> <p>Once the object has been saved, you must reload the object in order to access the actual value that was applied to the updated field:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">product</span> <span class="o">=</span> <span class="n">Products</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">pk</span><span class="o">=</span><span class="n">product</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">product</span><span class="o">.</span><span class="n">number_sold</span> <span class="go">42</span> </pre></div> </div> <p>For more details, see the documentation on <a class="reference internal" href="../../topics/db/queries.html#query-expressions"><em>F() expressions</em></a> and their <a class="reference internal" href="../../topics/db/queries.html#topics-db-queries-update"><em>use in update queries</em></a>.</p> </div> </div> <div class="section" id="s-deleting-objects"> <span id="deleting-objects"></span><h2>Deleting objects<a class="headerlink" href="#deleting-objects" title="Permalink to this headline">¶</a></h2> <dl class="method"> <dt id="django.db.models.Model.delete"> <tt class="descclassname">Model.</tt><tt class="descname">delete</tt>(<span class="optional">[</span><em>using=DEFAULT_DB_ALIAS</em><span class="optional">]</span>)<a class="headerlink" href="#django.db.models.Model.delete" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.2:</span> The <tt class="docutils literal"><span class="pre">using</span></tt> argument was added.</div> <p>Issues a SQL <tt class="docutils literal"><span class="pre">DELETE</span></tt> for the object. This only deletes the object in the database; the Python instance will still exist and will still have data in its fields.</p> <p>For more details, including how to delete objects in bulk, see <a class="reference internal" href="../../topics/db/queries.html#topics-db-queries-delete"><em>Deleting objects</em></a>.</p> <p>If you want customized deletion behavior, you can override the <tt class="docutils literal"><span class="pre">delete()</span></tt> method. See <a class="reference internal" href="../../topics/db/models.html#overriding-model-methods"><em>Overriding predefined model methods</em></a> for more details.</p> </div> <div class="section" id="s-other-model-instance-methods"> <span id="s-model-instance-methods"></span><span id="other-model-instance-methods"></span><span id="model-instance-methods"></span><h2>Other model instance methods<a class="headerlink" href="#other-model-instance-methods" title="Permalink to this headline">¶</a></h2> <p>A few object methods have special purposes.</p> <div class="section" id="s-unicode"> <span id="unicode"></span><h3><tt class="docutils literal"><span class="pre">__unicode__</span></tt><a class="headerlink" href="#unicode" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="django.db.models.Model.__unicode__"> <tt class="descclassname">Model.</tt><tt class="descname">__unicode__</tt>()<a class="headerlink" href="#django.db.models.Model.__unicode__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The <tt class="docutils literal"><span class="pre">__unicode__()</span></tt> method is called whenever you call <tt class="docutils literal"><span class="pre">unicode()</span></tt> on an object. Django uses <tt class="docutils literal"><span class="pre">unicode(obj)</span></tt> (or the related function, <a class="reference internal" href="#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">str(obj)</span></tt></a>) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the <tt class="docutils literal"><span class="pre">__unicode__()</span></tt> method.</p> <p>For example:</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">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="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="s">u'</span><span class="si">%s</span><span class="s"> </span><span class="si">%s</span><span class="s">'</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> </pre></div> </div> <p>If you define a <tt class="docutils literal"><span class="pre">__unicode__()</span></tt> method on your model and not a <a class="reference internal" href="#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> method, Django will automatically provide you with a <a class="reference internal" href="#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> that calls <tt class="docutils literal"><span class="pre">__unicode__()</span></tt> and then converts the result correctly to a UTF-8 encoded string object. This is recommended development practice: define only <tt class="docutils literal"><span class="pre">__unicode__()</span></tt> and let Django take care of the conversion to string objects when required.</p> </div> <div class="section" id="s-str"> <span id="str"></span><h3><tt class="docutils literal"><span class="pre">__str__</span></tt><a class="headerlink" href="#str" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="django.db.models.Model.__str__"> <tt class="descclassname">Model.</tt><tt class="descname">__str__</tt>()<a class="headerlink" href="#django.db.models.Model.__str__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The <tt class="docutils literal"><span class="pre">__str__()</span></tt> method is called whenever you call <tt class="docutils literal"><span class="pre">str()</span></tt> on an object. The main use for this method directly inside Django is when the <tt class="docutils literal"><span class="pre">repr()</span></tt> output of a model is displayed anywhere (for example, in debugging output). Thus, you should return a nice, human-readable string for the object’s <tt class="docutils literal"><span class="pre">__str__()</span></tt>. It isn’t required to put <tt class="docutils literal"><span class="pre">__str__()</span></tt> methods everywhere if you have sensible <a class="reference internal" href="#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> methods.</p> <p>The previous <a class="reference internal" href="#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> example could be similarly written using <tt class="docutils literal"><span class="pre">__str__()</span></tt> 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">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="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c"># Note use of django.utils.encoding.smart_str() here because</span> <span class="c"># first_name and last_name will be unicode strings.</span> <span class="k">return</span> <span class="n">smart_str</span><span class="p">(</span><span class="s">'</span><span class="si">%s</span><span class="s"> </span><span class="si">%s</span><span class="s">'</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> </pre></div> </div> </div> <div class="section" id="s-get-absolute-url"> <span id="get-absolute-url"></span><h3><tt class="docutils literal"><span class="pre">get_absolute_url</span></tt><a class="headerlink" href="#get-absolute-url" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="django.db.models.Model.get_absolute_url"> <tt class="descclassname">Model.</tt><tt class="descname">get_absolute_url</tt>()<a class="headerlink" href="#django.db.models.Model.get_absolute_url" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Define a <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">"/people/</span><span class="si">%i</span><span class="s">/"</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">id</span> </pre></div> </div> <p>(Whilst this code is correct and simple, it may not be the most portable way to write this kind of method. The <a class="reference internal" href="#django.db.models.permalink" title="django.db.models.permalink"><tt class="xref py py-func docutils literal"><span class="pre">permalink()</span> <span class="pre">decorator</span></tt></a>, documented below, is usually the best approach and you should read that section before diving into code implementation.)</p> <p>One place Django uses <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> is in the admin app. If an object defines this method, the object-editing page will have a “View on site” link that will jump you directly to the object’s public view, as given by <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt>.</p> <p>Similarly, a couple of other bits of Django, such as the <a class="reference internal" href="../contrib/syndication.html"><em>syndication feed framework</em></a>, use <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> when it is defined. If it makes sense for your model’s instances to each have a unique URL, you should define <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt>.</p> <p>It’s good practice to use <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> in templates, instead of hard-coding your objects’ URLs. For example, this template code is bad:</p> <div class="highlight-python"><pre><!-- BAD template code. Avoid! --> <a href="/people/{{ object.id }}/">{{ object.name }}</a></pre> </div> <p>This template code is much better:</p> <div class="highlight-python"><pre><a href="{{ object.get_absolute_url }}">{{ object.name }}</a></pre> </div> <p>The logic here is that if you change the URL structure of your objects, even for something simple such as correcting a spelling error, you don’t want to have to track down every place that the URL might be created. Specify it once, in <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> and have all your other code call that one place.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>The string you return from <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> <strong>must</strong> contain only ASCII characters (required by the URI specfication, <span class="target" id="index-0"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc2396.html"><strong>RFC 2396</strong></a>) and be URL-encoded, if necessary.</p> <p class="last">Code and templates calling <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> should be able to use the result directly without any further processing. You may wish to use the <tt class="docutils literal"><span class="pre">django.utils.encoding.iri_to_uri()</span></tt> function to help with this if you are using unicode strings containing characters outside the ASCII range at all.</p> </div> <div class="section" id="s-the-permalink-decorator"> <span id="the-permalink-decorator"></span><h4>The <tt class="docutils literal"><span class="pre">permalink</span></tt> decorator<a class="headerlink" href="#the-permalink-decorator" title="Permalink to this headline">¶</a></h4> <p>The way we wrote <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> above is a slightly violation of the DRY principle: the URL for this object is defined both in the URLconf file and in the model.</p> <p>You can decouple your models from the URLconf using the <tt class="docutils literal"><span class="pre">permalink</span></tt> decorator:</p> <dl class="function"> <dt id="django.db.models.permalink"> <tt class="descname">permalink</tt>()<a class="headerlink" href="#django.db.models.permalink" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This decorator takes the name of a URL pattern (either a view name or a URL pattern name) and a list of position or keyword arguments and uses the URLconf patterns to construct the correct, full URL. It returns a string for the correct URL, with all parameters substituted in the correct positions.</p> <p>The <tt class="docutils literal"><span class="pre">permalink</span></tt> decorator is a Python-level equivalent to the <a class="reference internal" href="../templates/builtins.html#std:templatetag-url"><tt class="xref std std-ttag docutils literal"><span class="pre">url</span></tt></a> template tag and a high-level wrapper for the <a class="reference internal" href="../../topics/http/urls.html#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-func docutils literal"><span class="pre">django.core.urlresolvers.reverse()</span></tt></a> function.</p> <p>An example should make it clear how to use <tt class="docutils literal"><span class="pre">permalink()</span></tt>. Suppose your URLconf contains a line such as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="s">r'^people/(\d+)/$'</span><span class="p">,</span> <span class="s">'people.views.details'</span><span class="p">),</span> </pre></div> </div> <p>...your model could have a <a class="reference internal" href="#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> method that looked like this:</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="nd">@models.permalink</span> <span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="p">(</span><span class="s">'people.views.details'</span><span class="p">,</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span> </pre></div> </div> <p>Similarly, if you had a URLconf entry that looked like:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="s">r'/archive/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$'</span><span class="p">,</span> <span class="n">archive_view</span><span class="p">)</span> </pre></div> </div> <p>...you could reference this using <tt class="docutils literal"><span class="pre">permalink()</span></tt> as follows:</p> <div class="highlight-python"><div class="highlight"><pre><span class="nd">@models.permalink</span> <span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="p">(</span><span class="s">'archive_view'</span><span class="p">,</span> <span class="p">(),</span> <span class="p">{</span> <span class="s">'year'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">created</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="s">'month'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">created</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">'%m'</span><span class="p">),</span> <span class="s">'day'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">created</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">'</span><span class="si">%d</span><span class="s">'</span><span class="p">)})</span> </pre></div> </div> <p>Notice that we specify an empty sequence for the second parameter in this case, because we only want to pass keyword parameters, not positional ones.</p> <p>In this way, you’re associating the model’s absolute path with the view that is used to display it, without repeating the view’s URL information anywhere. You can still use the <a class="reference internal" href="#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> method in templates, as before.</p> <p>In some cases, such as the use of generic views or the re-use of custom views for multiple models, specifying the view function may confuse the reverse URL matcher (because multiple patterns point to the same view). For that case, Django has <a class="reference internal" href="../../topics/http/urls.html#naming-url-patterns"><em>named URL patterns</em></a>. Using a named URL pattern, it’s possible to give a name to a pattern, and then reference the name rather than the view function. A named URL pattern is defined by replacing the pattern tuple by a call to the <tt class="docutils literal"><span class="pre">url</span></tt> function):</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^people/(\d+)/$'</span><span class="p">,</span> <span class="s">'blog_views.generic_detail'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'people_view'</span><span class="p">),</span> </pre></div> </div> <p>...and then using that name to perform the reverse URL resolution instead of the view name:</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="nd">@models.permalink</span> <span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="p">(</span><span class="s">'people_view'</span><span class="p">,</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">id</span><span class="p">)])</span> </pre></div> </div> <p>More details on named URL patterns are in the <a class="reference internal" href="../../topics/http/urls.html"><em>URL dispatch documentation</em></a>.</p> </div> </div> </div> <div class="section" id="s-extra-instance-methods"> <span id="extra-instance-methods"></span><h2>Extra instance methods<a class="headerlink" href="#extra-instance-methods" title="Permalink to this headline">¶</a></h2> <p>In addition to <a class="reference internal" href="#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>, <a class="reference internal" href="#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>, a model object might have some of the following methods:</p> <dl class="method"> <dt id="django.db.models.Model.get_FOO_display"> <tt class="descclassname">Model.</tt><tt class="descname">get_FOO_display</tt>()<a class="headerlink" href="#django.db.models.Model.get_FOO_display" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>For every field that has <a class="reference internal" href="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> set, the object will have a <tt class="docutils literal"><span class="pre">get_FOO_display()</span></tt> method, where <tt class="docutils literal"><span class="pre">FOO</span></tt> is the name of the field. This method returns the “human-readable” value of the field.</p> <p>For example:</p> <div class="highlight-python"><pre> from django.db import models class Person(models.Model): SHIRT_SIZES = ( (u'S', u'Small'), (u'M', u'Medium'), (u'L', u'Large'), ) name = models.CharField(max_length=60) shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES) :: >>> p = Person(name="Fred Flintstone", shirt_size="L") >>> p.save() >>> p.shirt_size u'L' >>> p.get_shirt_size_display() u'Large'</pre> </div> <dl class="method"> <dt id="django.db.models.Model.get_next_by_FOO"> <tt class="descclassname">Model.</tt><tt class="descname">get_next_by_FOO</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.Model.get_next_by_FOO" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="django.db.models.Model.get_previous_by_FOO"> <tt class="descclassname">Model.</tt><tt class="descname">get_previous_by_FOO</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.Model.get_previous_by_FOO" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>For every <a class="reference internal" href="fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">DateField</span></tt></a> and <a class="reference internal" href="fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><tt class="xref py py-class docutils literal"><span class="pre">DateTimeField</span></tt></a> that does not have <a class="reference internal" href="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=True</span></tt></a>, the object will have <tt class="docutils literal"><span class="pre">get_next_by_FOO()</span></tt> and <tt class="docutils literal"><span class="pre">get_previous_by_FOO()</span></tt> methods, where <tt class="docutils literal"><span class="pre">FOO</span></tt> is the name of the field. This returns the next and previous object with respect to the date field, raising a <tt class="xref py py-exc docutils literal"><span class="pre">DoesNotExist</span></tt> exception when appropriate.</p> <p>Both methods accept optional keyword arguments, which should be in the format described in <a class="reference internal" href="querysets.html#field-lookups"><em>Field lookups</em></a>.</p> <p>Note that in the case of identical date values, these methods will use the primary key as a tie-breaker. This guarantees that no records are skipped or duplicated. That also means you cannot use those methods on unsaved objects.</p> </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="#">Model instance reference</a><ul> <li><a class="reference internal" href="#creating-objects">Creating objects</a></li> <li><a class="reference internal" href="#validating-objects">Validating objects</a></li> <li><a class="reference internal" href="#saving-objects">Saving objects</a><ul> <li><a class="reference internal" href="#auto-incrementing-primary-keys">Auto-incrementing primary keys</a><ul> <li><a class="reference internal" href="#the-pk-property">The <tt class="docutils literal"><span class="pre">pk</span></tt> property</a></li> <li><a class="reference internal" href="#explicitly-specifying-auto-primary-key-values">Explicitly specifying auto-primary-key values</a></li> </ul> </li> <li><a class="reference internal" href="#what-happens-when-you-save">What happens when you save?</a></li> <li><a class="reference internal" href="#how-django-knows-to-update-vs-insert">How Django knows to UPDATE vs. INSERT</a><ul> <li><a class="reference internal" href="#forcing-an-insert-or-update">Forcing an INSERT or UPDATE</a></li> </ul> </li> <li><a class="reference internal" href="#updating-attributes-based-on-existing-fields">Updating attributes based on existing fields</a></li> </ul> </li> <li><a class="reference internal" href="#deleting-objects">Deleting objects</a></li> <li><a class="reference internal" href="#other-model-instance-methods">Other model instance methods</a><ul> <li><a class="reference internal" href="#unicode"><tt class="docutils literal"><span class="pre">__unicode__</span></tt></a></li> <li><a class="reference internal" href="#str"><tt class="docutils literal"><span class="pre">__str__</span></tt></a></li> <li><a class="reference internal" href="#get-absolute-url"><tt class="docutils literal"><span class="pre">get_absolute_url</span></tt></a><ul> <li><a class="reference internal" href="#the-permalink-decorator">The <tt class="docutils literal"><span class="pre">permalink</span></tt> decorator</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#extra-instance-methods">Extra instance methods</a></li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="options.html">Model <tt class="docutils literal"><span class="pre">Meta</span></tt> options</a></li> <li>Next: <a href="querysets.html">QuerySet API reference</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../../index.html">Django 1.4.20 documentation</a> <ul><li><a href="../index.html">API Reference</a> <ul><li><a href="index.html">Models</a> <ul><li>Model instance reference</li></ul> </li></ul></li></ul> </li> </ul> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/ref/models/instances.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" /> <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">Mar 19, 2015</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="options.html" title="Model <tt class="docutils literal"><span class="pre">Meta</span></tt> options">previous</a> | <a href="../index.html" title="API Reference" accesskey="U">up</a> | <a href="querysets.html" title="QuerySet API reference">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>