Sophie

Sophie

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

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>Serializing Django objects &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="Using Django" href="index.html" />
    <link rel="next" title="Django settings" href="settings.html" />
    <link rel="prev" title="Pagination" href="pagination.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="pagination.html" title="Pagination">previous</a> 
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="settings.html" title="Django settings">next</a> &raquo;</div>
    </div>
    
    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-serialization">
            
  <div class="section" id="s-serializing-django-objects">
<span id="serializing-django-objects"></span><h1>Serializing Django objects<a class="headerlink" href="#serializing-django-objects" title="Permalink to this headline">¶</a></h1>
<p>Django&#8217;s serialization framework provides a mechanism for &#8220;translating&#8221; Django
objects into other formats. Usually these other formats will be text-based and
used for sending Django objects over a wire, but it&#8217;s possible for a
serializer to handle any format (text-based or not).</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">If you just want to get some data from your tables into a serialized
form, you could use the <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span></tt></a> management command.</p>
</div>
<div class="section" id="s-serializing-data">
<span id="serializing-data"></span><h2>Serializing data<a class="headerlink" href="#serializing-data" title="Permalink to this headline">¶</a></h2>
<p>At the highest level, serializing data is a very simple operation:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">serializers</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s">&quot;xml&quot;</span><span class="p">,</span> <span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
<p>The arguments to the <tt class="docutils literal"><span class="pre">serialize</span></tt> function are the format to serialize the data
to (see <a class="reference internal" href="#id1">Serialization formats</a>) and a <tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt> to
serialize. (Actually, the second argument can be any iterator that yields Django
objects, but it'll almost always be a QuerySet).</p>
<p>You can also use a serializer object directly:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">XMLSerializer</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">get_serializer</span><span class="p">(</span><span class="s">&quot;xml&quot;</span><span class="p">)</span>
<span class="n">xml_serializer</span> <span class="o">=</span> <span class="n">XMLSerializer</span><span class="p">()</span>
<span class="n">xml_serializer</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="n">queryset</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">xml_serializer</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>
</div>
<p>This is useful if you want to serialize data directly to a file-like object
(which includes an <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">out</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&quot;file.xml&quot;</span><span class="p">,</span> <span class="s">&quot;w&quot;</span><span class="p">)</span>
<span class="n">xml_serializer</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="n">stream</span><span class="o">=</span><span class="n">out</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-subset-of-fields">
<span id="subset-of-fields"></span><h3>Subset of fields<a class="headerlink" href="#subset-of-fields" title="Permalink to this headline">¶</a></h3>
<p>If you only want a subset of fields to be serialized, you can
specify a <tt class="docutils literal"><span class="pre">fields</span></tt> argument to the serializer:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">serializers</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s">&#39;xml&#39;</span><span class="p">,</span> <span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="n">fields</span><span class="o">=</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">,</span><span class="s">&#39;size&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>In this example, only the <tt class="docutils literal"><span class="pre">name</span></tt> and <tt class="docutils literal"><span class="pre">size</span></tt> attributes of each model will
be serialized.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Depending on your model, you may find that it is not possible to
deserialize a model that only serializes a subset of its fields. If a
serialized object doesn't specify all the fields that are required by a
model, the deserializer will not be able to save deserialized instances.</p>
</div>
</div>
<div class="section" id="s-inherited-models">
<span id="inherited-models"></span><h3>Inherited Models<a class="headerlink" href="#inherited-models" title="Permalink to this headline">¶</a></h3>
<p>If you have a model that is defined using an <a class="reference internal" href="db/models.html#abstract-base-classes"><em>abstract base class</em></a>, you don't have to do anything special to serialize
that model. Just call the serializer on the object (or objects) that you want to
serialize, and the output will be a complete representation of the serialized
object.</p>
<p>However, if you have a model that uses <a class="reference internal" href="db/models.html#multi-table-inheritance"><em>multi-table inheritance</em></a>, you also need to serialize all of the base classes
for the model. This is because only the fields that are locally defined on the
model will be serialized. For example, consider the following models:</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="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>
</pre></div>
</div>
<p>If you only serialize the Restaurant model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s">&#39;xml&#39;</span><span class="p">,</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
<p>the fields on the serialized output will only contain the <cite>serves_hot_dogs</cite>
attribute. The <cite>name</cite> attribute of the base class will be ignored.</p>
<p>In order to fully serialize your Restaurant instances, you will need to
serialize the Place models as well:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">all_objects</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span> <span class="o">+</span> <span class="nb">list</span><span class="p">(</span><span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s">&#39;xml&#39;</span><span class="p">,</span> <span class="n">all_objects</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-deserializing-data">
<span id="deserializing-data"></span><h2>Deserializing data<a class="headerlink" href="#deserializing-data" title="Permalink to this headline">¶</a></h2>
<p>Deserializing data is also a fairly simple operation:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s">&quot;xml&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="n">do_something_with</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
</pre></div>
</div>
<p>As you can see, the <tt class="docutils literal"><span class="pre">deserialize</span></tt> function takes the same format argument as
<tt class="docutils literal"><span class="pre">serialize</span></tt>, a string or stream of data, and returns an iterator.</p>
<p>However, here it gets slightly complicated. The objects returned by the
<tt class="docutils literal"><span class="pre">deserialize</span></tt> iterator <em>aren't</em> simple Django objects. Instead, they are
special <tt class="docutils literal"><span class="pre">DeserializedObject</span></tt> instances that wrap a created -- but unsaved --
object and any associated relationship data.</p>
<p>Calling <tt class="docutils literal"><span class="pre">DeserializedObject.save()</span></tt> saves the object to the database.</p>
<p>This ensures that deserializing is a non-destructive operation even if the
data in your serialized representation doesn't match what's currently in the
database. Usually, working with these <tt class="docutils literal"><span class="pre">DeserializedObject</span></tt> instances looks
something like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">deserialized_object</span> <span class="ow">in</span> <span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s">&quot;xml&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">object_should_be_saved</span><span class="p">(</span><span class="n">deserialized_object</span><span class="p">):</span>
        <span class="n">deserialized_object</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>In other words, the usual use is to examine the deserialized objects to make
sure that they are &quot;appropriate&quot; for saving before doing so.  Of course, if you
trust your data source you could just save the object and move on.</p>
<p>The Django object itself can be inspected as <tt class="docutils literal"><span class="pre">deserialized_object.object</span></tt>.</p>
</div>
<div class="section" id="s-serialization-formats">
<span id="s-id1"></span><span id="serialization-formats"></span><span id="id1"></span><h2>Serialization formats<a class="headerlink" href="#serialization-formats" title="Permalink to this headline">¶</a></h2>
<p>Django supports a number of serialization formats, some of which require you
to install third-party Python modules:</p>
<table class="docutils">
<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Identifier</th>
<th class="head">Information</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">xml</span></tt></td>
<td>Serializes to and from a simple XML dialect.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">json</span></tt></td>
<td>Serializes to and from <a class="reference external" href="http://json.org/">JSON</a> (using a version of <a class="reference external" href="http://undefined.org/python/#simplejson">simplejson</a>
bundled with Django).</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">yaml</span></tt></td>
<td>Serializes to YAML (YAML Ain't a Markup Language). This
serializer is only available if <a class="reference external" href="http://www.pyyaml.org/">PyYAML</a> is installed.</td>
</tr>
</tbody>
</table>
<div class="section" id="s-notes-for-specific-serialization-formats">
<span id="notes-for-specific-serialization-formats"></span><h3>Notes for specific serialization formats<a class="headerlink" href="#notes-for-specific-serialization-formats" title="Permalink to this headline">¶</a></h3>
<div class="section" id="s-id2">
<span id="id2"></span><h4>json<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h4>
<p>If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
serializer, you must pass <tt class="docutils literal"><span class="pre">ensure_ascii=False</span></tt> as a parameter to the
<tt class="docutils literal"><span class="pre">serialize()</span></tt> call. Otherwise, the output won't be encoded correctly.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">json_serializer</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">get_serializer</span><span class="p">(</span><span class="s">&quot;json&quot;</span><span class="p">)()</span>
<span class="n">json_serializer</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="n">queryset</span><span class="p">,</span> <span class="n">ensure_ascii</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">stream</span><span class="o">=</span><span class="n">response</span><span class="p">)</span>
</pre></div>
</div>
<p>The Django source code includes the <a class="reference external" href="http://undefined.org/python/#simplejson">simplejson</a> module. However, if you're
using Python 2.6 or later (which includes a builtin version of the module), Django will
use the builtin <tt class="docutils literal"><span class="pre">json</span></tt> module automatically. If you have a system installed
version that includes the C-based speedup extension, or your system version is
more recent than the version shipped with Django (currently, 2.0.7), the
system version will be used instead of the version included with Django.</p>
<p>Be aware that if you're serializing using that module directly, not all Django
output can be passed unmodified to simplejson. In particular, <a class="reference internal" href="i18n/internationalization.html#lazy-translations"><em>lazy
translation objects</em></a> need a <a class="reference external" href="http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html">special encoder</a> written for
them. Something like this will work:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils.functional</span> <span class="kn">import</span> <span class="n">Promise</span>
<span class="kn">from</span> <span class="nn">django.utils.encoding</span> <span class="kn">import</span> <span class="n">force_unicode</span>

<span class="k">class</span> <span class="nc">LazyEncoder</span><span class="p">(</span><span class="n">simplejson</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">Promise</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">force_unicode</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">LazyEncoder</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="s-natural-keys">
<span id="s-topics-serialization-natural-keys"></span><span id="natural-keys"></span><span id="topics-serialization-natural-keys"></span><h2>Natural keys<a class="headerlink" href="#natural-keys" 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>The default serialization strategy for foreign keys and many-to-many
relations is to serialize the value of the primary key(s) of the
objects in the relation. This strategy works well for most types of
object, but it can cause difficulty in some circumstances.</p>
<p>Consider the case of a list of objects that have foreign key on
<tt class="xref py py-class docutils literal"><span class="pre">ContentType</span></tt>. If you're going to serialize an object that
refers to a content type, you need to have a way to refer to that
content type. Content Types are automatically created by Django as
part of the database synchronization process, so you don't need to
include content types in a fixture or other serialized data. As a
result, the primary key of any given content type isn't easy to
predict - it will depend on how and when <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> was
executed to create the content types.</p>
<p>There is also the matter of convenience. An integer id isn't always
the most convenient way to refer to an object; sometimes, a
more natural reference would be helpful.</p>
<p>It is for these reasons that Django provides <em>natural keys</em>. A natural
key is a tuple of values that can be used to uniquely identify an
object instance without using the primary key value.</p>
<div class="section" id="s-deserialization-of-natural-keys">
<span id="deserialization-of-natural-keys"></span><h3>Deserialization of natural keys<a class="headerlink" href="#deserialization-of-natural-keys" title="Permalink to this headline">¶</a></h3>
<p>Consider the following two models:</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">100</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">100</span><span class="p">)</span>

    <span class="n">birthdate</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="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">((</span><span class="s">&#39;first_name&#39;</span><span class="p">,</span> <span class="s">&#39;last_name&#39;</span><span class="p">),)</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">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">author</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>
</pre></div>
</div>
<p>Ordinarily, serialized data for <tt class="docutils literal"><span class="pre">Book</span></tt> would use an integer to refer to
the author. For example, in JSON, a Book might be serialized as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">...</span>
<span class="p">{</span>
    <span class="s">&quot;pk&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&quot;model&quot;</span><span class="p">:</span> <span class="s">&quot;store.book&quot;</span><span class="p">,</span>
    <span class="s">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&quot;name&quot;</span><span class="p">:</span> <span class="s">&quot;Mostly Harmless&quot;</span><span class="p">,</span>
        <span class="s">&quot;author&quot;</span><span class="p">:</span> <span class="mi">42</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This isn't a particularly natural way to refer to an author. It
requires that you know the primary key value for the author; it also
requires that this primary key value is stable and predictable.</p>
<p>However, if we add natural key handling to Person, the fixture becomes
much more humane. To add natural key handling, you define a default
Manager for Person with a <tt class="docutils literal"><span class="pre">get_by_natural_key()</span></tt> method. In the case
of a Person, a good natural key might be the pair of first and last
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="k">class</span> <span class="nc">PersonManager</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">get_by_natural_key</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="n">last_name</span><span class="p">)</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">objects</span> <span class="o">=</span> <span class="n">PersonManager</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">100</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">100</span><span class="p">)</span>

    <span class="n">birthdate</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="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">((</span><span class="s">&#39;first_name&#39;</span><span class="p">,</span> <span class="s">&#39;last_name&#39;</span><span class="p">),)</span>
</pre></div>
</div>
<p>Now books can use that natural key to refer to <tt class="docutils literal"><span class="pre">Person</span></tt> objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">...</span>
<span class="p">{</span>
    <span class="s">&quot;pk&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&quot;model&quot;</span><span class="p">:</span> <span class="s">&quot;store.book&quot;</span><span class="p">,</span>
    <span class="s">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&quot;name&quot;</span><span class="p">:</span> <span class="s">&quot;Mostly Harmless&quot;</span><span class="p">,</span>
        <span class="s">&quot;author&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s">&quot;Douglas&quot;</span><span class="p">,</span> <span class="s">&quot;Adams&quot;</span><span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="o">...</span>
</pre></div>
</div>
<p>When you try to load this serialized data, Django will use the
<tt class="docutils literal"><span class="pre">get_by_natural_key()</span></tt> method to resolve <tt class="docutils literal"><span class="pre">[&quot;Douglas&quot;,</span> <span class="pre">&quot;Adams&quot;]</span></tt>
into the primary key of an actual <tt class="docutils literal"><span class="pre">Person</span></tt> object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Whatever fields you use for a natural key must be able to uniquely
identify an object. This will usually mean that your model will
have a uniqueness clause (either unique=True on a single field, or
<tt class="docutils literal"><span class="pre">unique_together</span></tt> over multiple fields) for the field or fields
in your natural key. However, uniqueness doesn't need to be
enforced at the database level. If you are certain that a set of
fields will be effectively unique, you can still use those fields
as a natural key.</p>
</div>
</div>
<div class="section" id="s-serialization-of-natural-keys">
<span id="serialization-of-natural-keys"></span><h3>Serialization of natural keys<a class="headerlink" href="#serialization-of-natural-keys" title="Permalink to this headline">¶</a></h3>
<p>So how do you get Django to emit a natural key when serializing an object?
Firstly, you need to add another method -- this time to the model itself:</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">objects</span> <span class="o">=</span> <span class="n">PersonManager</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">100</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">100</span><span class="p">)</span>

    <span class="n">birthdate</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="k">def</span> <span class="nf">natural_key</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="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="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">((</span><span class="s">&#39;first_name&#39;</span><span class="p">,</span> <span class="s">&#39;last_name&#39;</span><span class="p">),)</span>
</pre></div>
</div>
<p>That method should always return a natural key tuple -- in this
example, <tt class="docutils literal"><span class="pre">(first</span> <span class="pre">name,</span> <span class="pre">last</span> <span class="pre">name)</span></tt>. Then, when you call
<tt class="docutils literal"><span class="pre">serializers.serialize()</span></tt>, you provide a <tt class="docutils literal"><span class="pre">use_natural_keys=True</span></tt>
argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s">&#39;json&#39;</span><span class="p">,</span> <span class="p">[</span><span class="n">book1</span><span class="p">,</span> <span class="n">book2</span><span class="p">],</span> <span class="n">indent</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">use_natural_keys</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>When <tt class="docutils literal"><span class="pre">use_natural_keys=True</span></tt> is specified, Django will use the
<tt class="docutils literal"><span class="pre">natural_key()</span></tt> method to serialize any reference to objects of the
type that defines the method.</p>
<p>If you are using <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span></tt></a> to generate serialized data, you
use the <cite>--natural</cite> command line flag to generate natural keys.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>You don't need to define both <tt class="docutils literal"><span class="pre">natural_key()</span></tt> and
<tt class="docutils literal"><span class="pre">get_by_natural_key()</span></tt>. If you don't want Django to output
natural keys during serialization, but you want to retain the
ability to load natural keys, then you can opt to not implement
the <tt class="docutils literal"><span class="pre">natural_key()</span></tt> method.</p>
<p class="last">Conversely, if (for some strange reason) you want Django to output
natural keys during serialization, but <em>not</em> be able to load those
key values, just don't define the <tt class="docutils literal"><span class="pre">get_by_natural_key()</span></tt> method.</p>
</div>
</div>
<div class="section" id="s-dependencies-during-serialization">
<span id="dependencies-during-serialization"></span><h3>Dependencies during serialization<a class="headerlink" href="#dependencies-during-serialization" title="Permalink to this headline">¶</a></h3>
<p>Since natural keys rely on database lookups to resolve references, it
is important that data exists before it is referenced. You can't make
a <cite>forward reference</cite> with natural keys - the data you are referencing
must exist before you include a natural key reference to that data.</p>
<p>To accommodate this limitation, calls to <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span></tt></a> that use
the <a class="reference internal" href="../ref/django-admin.html#django-admin-option---natural"><tt class="xref std std-djadminopt docutils literal"><span class="pre">--natural</span></tt></a> option will serialize any model with a
<tt class="docutils literal"><span class="pre">natural_key()</span></tt> method before it serializes normal key objects.</p>
<p>However, this may not always be enough. If your natural key refers to
another object (by using a foreign key or natural key to another object
as part of a natural key), then you need to be able to ensure that
the objects on which a natural key depends occur in the serialized data
before the natural key requires them.</p>
<p>To control this ordering, you can define dependencies on your
<tt class="docutils literal"><span class="pre">natural_key()</span></tt> methods. You do this by setting a <tt class="docutils literal"><span class="pre">dependencies</span></tt>
attribute on the <tt class="docutils literal"><span class="pre">natural_key()</span></tt> method itself.</p>
<p>For example, consider the <tt class="docutils literal"><span class="pre">Permission</span></tt> model in <tt class="docutils literal"><span class="pre">contrib.auth</span></tt>.
The following is a simplified version of the <tt class="docutils literal"><span class="pre">Permission</span></tt> model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Permission</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">content_type</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">ContentType</span><span class="p">)</span>
    <span class="n">codename</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="c"># ...</span>
    <span class="k">def</span> <span class="nf">natural_key</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="bp">self</span><span class="o">.</span><span class="n">codename</span><span class="p">,)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">content_type</span><span class="o">.</span><span class="n">natural_key</span><span class="p">()</span>
</pre></div>
</div>
<p>The natural key for a <tt class="docutils literal"><span class="pre">Permission</span></tt> is a combination of the codename for the
<tt class="docutils literal"><span class="pre">Permission</span></tt>, and the <tt class="docutils literal"><span class="pre">ContentType</span></tt> to which the <tt class="docutils literal"><span class="pre">Permission</span></tt> applies. This means
that <tt class="docutils literal"><span class="pre">ContentType</span></tt> must be serialized before <tt class="docutils literal"><span class="pre">Permission</span></tt>. To define this
dependency, we add one extra line:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Permission</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="k">def</span> <span class="nf">natural_key</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="bp">self</span><span class="o">.</span><span class="n">codename</span><span class="p">,)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">content_type</span><span class="o">.</span><span class="n">natural_key</span><span class="p">()</span>
    <span class="n">natural_key</span><span class="o">.</span><span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;contenttypes.contenttype&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>This definition ensures that <tt class="docutils literal"><span class="pre">ContentType</span></tt> models are serialized before
<tt class="docutils literal"><span class="pre">Permission</span></tt> models. In turn, any object referencing <tt class="docutils literal"><span class="pre">Permission</span></tt> will
be serialized after both <tt class="docutils literal"><span class="pre">ContentType</span></tt> and <tt class="docutils literal"><span class="pre">Permission</span></tt>.</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="#">Serializing Django objects</a><ul>
<li><a class="reference internal" href="#serializing-data">Serializing data</a><ul>
<li><a class="reference internal" href="#subset-of-fields">Subset of fields</a></li>
<li><a class="reference internal" href="#inherited-models">Inherited Models</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deserializing-data">Deserializing data</a></li>
<li><a class="reference internal" href="#serialization-formats">Serialization formats</a><ul>
<li><a class="reference internal" href="#notes-for-specific-serialization-formats">Notes for specific serialization formats</a><ul>
<li><a class="reference internal" href="#id2">json</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#natural-keys">Natural keys</a><ul>
<li><a class="reference internal" href="#deserialization-of-natural-keys">Deserialization of natural keys</a></li>
<li><a class="reference internal" href="#serialization-of-natural-keys">Serialization of natural keys</a></li>
<li><a class="reference internal" href="#dependencies-during-serialization">Dependencies during serialization</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="pagination.html">Pagination</a></li>
    
    
      <li>Next: <a href="settings.html">Django settings</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>Serializing Django objects</li></ul>
        </li></ul>
      </li>
  </ul>  

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/topics/serialization.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="pagination.html" title="Pagination">previous</a> 
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="settings.html" title="Django settings">next</a> &raquo;</div>
    </div>
  </div>

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