<!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>Writing custom model fields — Django 1.4.18 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.18', 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.18 documentation" href="../index.html" /> <link rel="up" title="“How-to” guides" href="index.html" /> <link rel="next" title="Custom template tags and filters" href="custom-template-tags.html" /> <link rel="prev" title="Writing custom django-admin commands" href="custom-management-commands.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 1.4.18 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="custom-management-commands.html" title="Writing custom django-admin commands">previous</a> | <a href="index.html" title="&#8220;How-to&#8221; guides" accesskey="U">up</a> | <a href="custom-template-tags.html" title="Custom template tags and filters">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="howto-custom-model-fields"> <div class="section" id="s-writing-custom-model-fields"> <span id="writing-custom-model-fields"></span><h1>Writing custom model fields<a class="headerlink" href="#writing-custom-model-fields" title="Permalink to this headline">¶</a></h1> <div class="section" id="s-introduction"> <span id="introduction"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="../topics/db/models.html"><em>model reference</em></a> documentation explains how to use Django’s standard field classes – <a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a>, <a class="reference internal" href="../ref/models/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>, etc. For many purposes, those classes are all you’ll need. Sometimes, though, the Django version won’t meet your precise requirements, or you’ll want to use a field that is entirely different from those shipped with Django.</p> <p>Django’s built-in field types don’t cover every possible database column type – only the common types, such as <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> and <tt class="docutils literal"><span class="pre">INTEGER</span></tt>. For more obscure column types, such as geographic polygons or even user-created types such as <a class="reference external" href="http://www.postgresql.org/docs/8.2/interactive/sql-createtype.html">PostgreSQL custom types</a>, you can define your own Django <tt class="docutils literal"><span class="pre">Field</span></tt> subclasses.</p> <p>Alternatively, you may have a complex Python object that can somehow be serialized to fit into a standard database column type. This is another case where a <tt class="docutils literal"><span class="pre">Field</span></tt> subclass will help you use your object with your models.</p> <div class="section" id="s-our-example-object"> <span id="our-example-object"></span><h3>Our example object<a class="headerlink" href="#our-example-object" title="Permalink to this headline">¶</a></h3> <p>Creating custom fields requires a bit of attention to detail. To make things easier to follow, we’ll use a consistent example throughout this document: wrapping a Python object representing the deal of cards in a hand of <a class="reference external" href="http://en.wikipedia.org/wiki/Contract_bridge">Bridge</a>. Don’t worry, you don’t have know how to play Bridge to follow this example. You only need to know that 52 cards are dealt out equally to four players, who are traditionally called <em>north</em>, <em>east</em>, <em>south</em> and <em>west</em>. Our class looks something like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Hand</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">"""A hand of cards (bridge style)"""</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">):</span> <span class="c"># Input parameters are lists of cards ('Ah', '9s', etc)</span> <span class="bp">self</span><span class="o">.</span><span class="n">north</span> <span class="o">=</span> <span class="n">north</span> <span class="bp">self</span><span class="o">.</span><span class="n">east</span> <span class="o">=</span> <span class="n">east</span> <span class="bp">self</span><span class="o">.</span><span class="n">south</span> <span class="o">=</span> <span class="n">south</span> <span class="bp">self</span><span class="o">.</span><span class="n">west</span> <span class="o">=</span> <span class="n">west</span> <span class="c"># ... (other possibly useful methods omitted) ...</span> </pre></div> </div> <p>This is just an ordinary Python class, with nothing Django-specific about it. We’d like to be able to do things like this in our models (we assume the <tt class="docutils literal"><span class="pre">hand</span></tt> attribute on the model is an instance of <tt class="docutils literal"><span class="pre">Hand</span></tt>):</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">example</span> <span class="o">=</span> <span class="n">MyModel</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="mi">1</span><span class="p">)</span> <span class="k">print</span> <span class="n">example</span><span class="o">.</span><span class="n">hand</span><span class="o">.</span><span class="n">north</span> <span class="n">new_hand</span> <span class="o">=</span> <span class="n">Hand</span><span class="p">(</span><span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">)</span> <span class="n">example</span><span class="o">.</span><span class="n">hand</span> <span class="o">=</span> <span class="n">new_hand</span> <span class="n">example</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> <p>We assign to and retrieve from the <tt class="docutils literal"><span class="pre">hand</span></tt> attribute in our model just like any other Python class. The trick is to tell Django how to handle saving and loading such an object.</p> <p>In order to use the <tt class="docutils literal"><span class="pre">Hand</span></tt> class in our models, we <strong>do not</strong> have to change this class at all. This is ideal, because it means you can easily write model support for existing classes where you cannot change the source code.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">You might only be wanting to take advantage of custom database column types and deal with the data as standard Python types in your models; strings, or floats, for example. This case is similar to our <tt class="docutils literal"><span class="pre">Hand</span></tt> example and we’ll note any differences as we go along.</p> </div> </div> </div> <div class="section" id="s-background-theory"> <span id="background-theory"></span><h2>Background theory<a class="headerlink" href="#background-theory" title="Permalink to this headline">¶</a></h2> <div class="section" id="s-database-storage"> <span id="database-storage"></span><h3>Database storage<a class="headerlink" href="#database-storage" title="Permalink to this headline">¶</a></h3> <p>The simplest way to think of a model field is that it provides a way to take a normal Python object – string, boolean, <tt class="docutils literal"><span class="pre">datetime</span></tt>, or something more complex like <tt class="docutils literal"><span class="pre">Hand</span></tt> – and convert it to and from a format that is useful when dealing with the database (and serialization, but, as we’ll see later, that falls out fairly naturally once you have the database side under control).</p> <p>Fields in a model must somehow be converted to fit into an existing database column type. Different databases provide different sets of valid column types, but the rule is still the same: those are the only types you have to work with. Anything you want to store in the database must fit into one of those types.</p> <p>Normally, you’re either writing a Django field to match a particular database column type, or there’s a fairly straightforward way to convert your data to, say, a string.</p> <p>For our <tt class="docutils literal"><span class="pre">Hand</span></tt> example, we could convert the card data to a string of 104 characters by concatenating all the cards together in a pre-determined order – say, all the <em>north</em> cards first, then the <em>east</em>, <em>south</em> and <em>west</em> cards. So <tt class="docutils literal"><span class="pre">Hand</span></tt> objects can be saved to text or character columns in the database.</p> </div> <div class="section" id="s-what-does-a-field-class-do"> <span id="what-does-a-field-class-do"></span><h3>What does a field class do?<a class="headerlink" href="#what-does-a-field-class-do" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.db.models.Field"> <em class="property">class </em><tt class="descname">Field</tt><a class="headerlink" href="#django.db.models.Field" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>All of Django’s fields (and when we say <em>fields</em> in this document, we always mean model fields and not <a class="reference internal" href="../ref/forms/fields.html"><em>form fields</em></a>) are subclasses of <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Field</span></tt></a>. Most of the information that Django records about a field is common to all fields – name, help text, uniqueness and so forth. Storing all that information is handled by <tt class="docutils literal"><span class="pre">Field</span></tt>. We’ll get into the precise details of what <tt class="docutils literal"><span class="pre">Field</span></tt> can do later on; for now, suffice it to say that everything descends from <tt class="docutils literal"><span class="pre">Field</span></tt> and then customizes key pieces of the class behavior.</p> <p>It’s important to realize that a Django field class is not what is stored in your model attributes. The model attributes contain normal Python objects. The field classes you define in a model are actually stored in the <tt class="docutils literal"><span class="pre">Meta</span></tt> class when the model class is created (the precise details of how this is done are unimportant here). This is because the field classes aren’t necessary when you’re just creating and modifying attributes. Instead, they provide the machinery for converting between the attribute value and what is stored in the database or sent to the <a class="reference internal" href="../topics/serialization.html"><em>serializer</em></a>.</p> <p>Keep this in mind when creating your own custom fields. The Django <tt class="docutils literal"><span class="pre">Field</span></tt> subclass you write provides the machinery for converting between your Python instances and the database/serializer values in various ways (there are differences between storing a value and using a value for lookups, for example). If this sounds a bit tricky, don’t worry – it will become clearer in the examples below. Just remember that you will often end up creating two classes when you want a custom field:</p> <ul class="simple"> <li>The first class is the Python object that your users will manipulate. They will assign it to the model attribute, they will read from it for displaying purposes, things like that. This is the <tt class="docutils literal"><span class="pre">Hand</span></tt> class in our example.</li> <li>The second class is the <tt class="docutils literal"><span class="pre">Field</span></tt> subclass. This is the class that knows how to convert your first class back and forth between its permanent storage form and the Python form.</li> </ul> </div> </div> <div class="section" id="s-writing-a-field-subclass"> <span id="writing-a-field-subclass"></span><h2>Writing a field subclass<a class="headerlink" href="#writing-a-field-subclass" title="Permalink to this headline">¶</a></h2> <p>When planning your <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass, first give some thought to which existing <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class your new field is most similar to. Can you subclass an existing Django field and save yourself some work? If not, you should subclass the <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class, from which everything is descended.</p> <p>Initializing your new field is a matter of separating out any arguments that are specific to your case from the common arguments and passing the latter to the <a class="reference internal" href="#django.db.models.Field.__init__" title="django.db.models.Field.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method of <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> (or your parent class).</p> <p>In our example, we’ll call our field <tt class="docutils literal"><span class="pre">HandField</span></tt>. (It’s a good idea to call your <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass <tt class="docutils literal"><span class="pre"><Something>Field</span></tt>, so it’s easily identifiable as a <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass.) It doesn’t behave like any existing field, so we’ll subclass directly from <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>:</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">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="n">description</span> <span class="o">=</span> <span class="s">"A hand of cards (bridge style)"</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">'max_length'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">104</span> <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> </pre></div> </div> <p>Our <tt class="docutils literal"><span class="pre">HandField</span></tt> accepts most of the standard field options (see the list below), but we ensure it has a fixed length, since it only needs to hold 52 card values plus their suits; 104 characters in total.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>Many of Django’s model fields accept options that they don’t do anything with. For example, you can pass both <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a> and <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> to a <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.DateField</span></tt></a> and it will simply ignore the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a> parameter (<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> being set implies <tt class="docutils literal"><span class="pre">editable=False</span></tt>). No error is raised in this case.</p> <p class="last">This behavior simplifies the field classes, because they don’t need to check for options that aren’t necessary. They just pass all the options to the parent class and then don’t use them later on. It’s up to you whether you want your fields to be more strict about the options they select, or to use the simpler, more permissive behavior of the current fields.</p> </div> <dl class="method"> <dt id="django.db.models.Field.__init__"> <tt class="descclassname">Field.</tt><tt class="descname">__init__</tt>()<a class="headerlink" href="#django.db.models.Field.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The <a class="reference internal" href="#django.db.models.Field.__init__" title="django.db.models.Field.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method takes the following parameters:</p> <ul class="simple"> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a></li> <li><tt class="xref py py-attr docutils literal"><span class="pre">name</span></tt></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a></li> <li><tt class="xref py py-attr docutils literal"><span class="pre">max_length</span></tt></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><tt class="xref py py-attr docutils literal"><span class="pre">unique</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><tt class="xref py py-attr docutils literal"><span class="pre">db_index</span></tt></a></li> <li><tt class="xref py py-attr docutils literal"><span class="pre">rel</span></tt>: Used for related fields (like <a class="reference internal" href="../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>). For advanced use only.</li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><tt class="xref py py-attr docutils literal"><span class="pre">default</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a></li> <li><tt class="xref py py-attr docutils literal"><span class="pre">serialize</span></tt>: If <tt class="docutils literal"><span class="pre">False</span></tt>, the field will not be serialized when the model is passed to Django’s <a class="reference internal" href="../topics/serialization.html"><em>serializers</em></a>. Defaults to <tt class="docutils literal"><span class="pre">True</span></tt>.</li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_date" title="django.db.models.Field.unique_for_date"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_date</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_month" title="django.db.models.Field.unique_for_month"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_month</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_year" title="django.db.models.Field.unique_for_year"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_year</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.choices" title="django.db.models.Field.choices"><tt class="xref py py-attr docutils literal"><span class="pre">choices</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><tt class="xref py py-attr docutils literal"><span class="pre">help_text</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><tt class="xref py py-attr docutils literal"><span class="pre">db_column</span></tt></a></li> <li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_tablespace" title="django.db.models.Field.db_tablespace"><tt class="xref py py-attr docutils literal"><span class="pre">db_tablespace</span></tt></a>: Only for index creation, if the backend supports <a class="reference internal" href="../topics/db/tablespaces.html"><em>tablespaces</em></a>. You can usually ignore this option.</li> <li><tt class="xref py py-attr docutils literal"><span class="pre">auto_created</span></tt>: True if the field was automatically created, as for the <cite>OneToOneField</cite> used by model inheritance. For advanced use only.</li> </ul> <p>All of the options without an explanation in the above list have the same meaning they do for normal Django fields. See the <a class="reference internal" href="../ref/models/fields.html"><em>field documentation</em></a> for examples and details.</p> <div class="section" id="s-the-subfieldbase-metaclass"> <span id="the-subfieldbase-metaclass"></span><h3>The <tt class="docutils literal"><span class="pre">SubfieldBase</span></tt> metaclass<a class="headerlink" href="#the-subfieldbase-metaclass" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.db.models.django.db.models.SubfieldBase"> <em class="property">class </em><tt class="descclassname">django.db.models.</tt><tt class="descname">SubfieldBase</tt><a class="headerlink" href="#django.db.models.django.db.models.SubfieldBase" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>As we indicated in the <a class="reference internal" href="#introduction">introduction</a>, field subclasses are often needed for two reasons: either to take advantage of a custom database column type, or to handle complex Python types. Obviously, a combination of the two is also possible. If you’re only working with custom database column types and your model fields appear in Python as standard Python types direct from the database backend, you don’t need to worry about this section.</p> <p>If you’re handling custom Python types, such as our <tt class="docutils literal"><span class="pre">Hand</span></tt> class, we need to make sure that when Django initializes an instance of our model and assigns a database value to our custom field attribute, we convert that value into the appropriate Python object. The details of how this happens internally are a little complex, but the code you need to write in your <tt class="docutils literal"><span class="pre">Field</span></tt> class is simple: make sure your field subclass uses a special metaclass:</p> <p>For example:</p> <div class="highlight-python"><pre>class HandField(models.Field): description = "A hand of cards (bridge style)" __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): # ...</pre> </div> <p>This ensures that the <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> method, documented below, will always be called when the attribute is initialized.</p> <div class="section" id="s-modelforms-and-custom-fields"> <span id="modelforms-and-custom-fields"></span><h4>ModelForms and custom fields<a class="headerlink" href="#modelforms-and-custom-fields" title="Permalink to this headline">¶</a></h4> <p>If you use <a class="reference internal" href="#django.db.models.django.db.models.SubfieldBase" title="django.db.models.django.db.models.SubfieldBase"><tt class="xref py py-class docutils literal"><span class="pre">SubfieldBase</span></tt></a>, <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> will be called every time an instance of the field is assigned a value. This means that whenever a value may be assigned to the field, you need to ensure that it will be of the correct datatype, or that you handle any exceptions.</p> <p>This is especially important if you use <a class="reference internal" href="../topics/forms/modelforms.html"><em>ModelForms</em></a>. When saving a ModelForm, Django will use form values to instantiate model instances. However, if the cleaned form data can’t be used as valid input to the field, the normal form validation process will break.</p> <p>Therefore, you must ensure that the form field used to represent your custom field performs whatever input validation and data cleaning is necessary to convert user-provided form input into a <cite>to_python()</cite>-compatible model field value. This may require writing a custom form field, and/or implementing the <a class="reference internal" href="#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><tt class="xref py py-meth docutils literal"><span class="pre">formfield()</span></tt></a> method on your field to return a form field class whose <cite>to_python()</cite> returns the correct datatype.</p> </div> </div> <div class="section" id="s-documenting-your-custom-field"> <span id="documenting-your-custom-field"></span><h3>Documenting your custom field<a class="headerlink" href="#documenting-your-custom-field" title="Permalink to this headline">¶</a></h3> <dl class="attribute"> <dt id="django.db.models.Field.description"> <tt class="descclassname">Field.</tt><tt class="descname">description</tt><a class="headerlink" href="#django.db.models.Field.description" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>As always, you should document your field type, so users will know what it is. In addition to providing a docstring for it, which is useful for developers, you can also allow users of the admin app to see a short description of the field type via the <a class="reference internal" href="../ref/contrib/admin/admindocs.html"><em>django.contrib.admindocs</em></a> application. To do this simply provide descriptive text in a <tt class="docutils literal"><span class="pre">description</span></tt> class attribute of your custom field. In the above example, the description displayed by the <tt class="docutils literal"><span class="pre">admindocs</span></tt> application for a <tt class="docutils literal"><span class="pre">HandField</span></tt> will be ‘A hand of cards (bridge style)’.</p> </div> <div class="section" id="s-useful-methods"> <span id="useful-methods"></span><h3>Useful methods<a class="headerlink" href="#useful-methods" title="Permalink to this headline">¶</a></h3> <p>Once you’ve created your <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass and set up the <tt class="docutils literal"><span class="pre">__metaclass__</span></tt>, you might consider overriding a few standard methods, depending on your field’s behavior. The list of methods below is in approximately decreasing order of importance, so start from the top.</p> <div class="section" id="s-custom-database-types"> <span id="custom-database-types"></span><h4>Custom database types<a class="headerlink" href="#custom-database-types" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.db_type"> <tt class="descclassname">Field.</tt><tt class="descname">db_type</tt>(<em>self</em>, <em>connection</em>)<a class="headerlink" href="#django.db.models.Field.db_type" 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">connection</span></tt> argument was added to support multiple databases.</div> <p>Returns the database column data type for the <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>, taking into account the connection object, and the settings associated with it.</p> <p>Say you’ve created a PostgreSQL custom type called <tt class="docutils literal"><span class="pre">mytype</span></tt>. You can use this field with Django by subclassing <tt class="docutils literal"><span class="pre">Field</span></tt> and implementing the <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method, like so:</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">MytypeField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span> <span class="k">return</span> <span class="s">'mytype'</span> </pre></div> </div> <p>Once you have <tt class="docutils literal"><span class="pre">MytypeField</span></tt>, you can use it in any model, just like any other <tt class="docutils literal"><span class="pre">Field</span></tt> type:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">80</span><span class="p">)</span> <span class="n">something_else</span> <span class="o">=</span> <span class="n">MytypeField</span><span class="p">()</span> </pre></div> </div> <p>If you aim to build a database-agnostic application, you should account for differences in database column types. For example, the date/time column type in PostgreSQL is called <tt class="docutils literal"><span class="pre">timestamp</span></tt>, while the same column in MySQL is called <tt class="docutils literal"><span class="pre">datetime</span></tt>. The simplest way to handle this in a <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method is to check the <tt class="docutils literal"><span class="pre">connection.settings_dict['ENGINE']</span></tt> attribute.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyDateField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span> <span class="k">if</span> <span class="n">connection</span><span class="o">.</span><span class="n">settings_dict</span><span class="p">[</span><span class="s">'ENGINE'</span><span class="p">]</span> <span class="o">==</span> <span class="s">'django.db.backends.mysql'</span><span class="p">:</span> <span class="k">return</span> <span class="s">'datetime'</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s">'timestamp'</span> </pre></div> </div> <p>The <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method is only called by Django when the framework constructs the <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></tt> statements for your application – that is, when you first create your tables. It’s not called at any other time, so it can afford to execute slightly complex code, such as the <tt class="docutils literal"><span class="pre">connection.settings_dict</span></tt> check in the above example.</p> <p>Some database column types accept parameters, such as <tt class="docutils literal"><span class="pre">CHAR(25)</span></tt>, where the parameter <tt class="docutils literal"><span class="pre">25</span></tt> represents the maximum column length. In cases like these, it’s more flexible if the parameter is specified in the model rather than being hard-coded in the <tt class="docutils literal"><span class="pre">db_type()</span></tt> method. For example, it wouldn’t make much sense to have a <tt class="docutils literal"><span class="pre">CharMaxlength25Field</span></tt>, shown here:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># This is a silly example of hard-coded parameters.</span> <span class="k">class</span> <span class="nc">CharMaxlength25Field</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span> <span class="k">return</span> <span class="s">'char(25)'</span> <span class="c"># In the model:</span> <span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="c"># ...</span> <span class="n">my_field</span> <span class="o">=</span> <span class="n">CharMaxlength25Field</span><span class="p">()</span> </pre></div> </div> <p>The better way of doing this would be to make the parameter specifiable at run time – i.e., when the class is instantiated. To do that, just implement <a class="reference internal" href="#django.db.models.Field.__init__" title="django.db.models.Field.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">django.db.models.Field.__init__()</span></tt></a>, like so:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># This is a much more flexible example.</span> <span class="k">class</span> <span class="nc">BetterCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">max_length</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span> <span class="o">=</span> <span class="n">max_length</span> <span class="nb">super</span><span class="p">(</span><span class="n">BetterCharField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span> <span class="k">return</span> <span class="s">'char(</span><span class="si">%s</span><span class="s">)'</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span> <span class="c"># In the model:</span> <span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="c"># ...</span> <span class="n">my_field</span> <span class="o">=</span> <span class="n">BetterCharField</span><span class="p">(</span><span class="mi">25</span><span class="p">)</span> </pre></div> </div> <p>Finally, if your column requires truly complex SQL setup, return <tt class="docutils literal"><span class="pre">None</span></tt> from <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a>. This will cause Django’s SQL creation code to skip over this field. You are then responsible for creating the column in the right table in some other way, of course, but this gives you a way to tell Django to get out of the way.</p> </div> <div class="section" id="s-converting-database-values-to-python-objects"> <span id="converting-database-values-to-python-objects"></span><h4>Converting database values to Python objects<a class="headerlink" href="#converting-database-values-to-python-objects" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.to_python"> <tt class="descclassname">Field.</tt><tt class="descname">to_python</tt>(<em>self</em>, <em>value</em>)<a class="headerlink" href="#django.db.models.Field.to_python" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Converts a value as returned by your database (or a serializer) to a Python object.</p> <p>The default implementation simply returns <tt class="docutils literal"><span class="pre">value</span></tt>, for the common case in which the database backend already returns data in the correct format (as a Python string, for example).</p> <p>If your custom <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class deals with data structures that are more complex than strings, dates, integers or floats, then you’ll need to override this method. As a general rule, the method should deal gracefully with any of the following arguments:</p> <ul class="simple"> <li>An instance of the correct type (e.g., <tt class="docutils literal"><span class="pre">Hand</span></tt> in our ongoing example).</li> <li>A string (e.g., from a deserializer).</li> <li>Whatever the database returns for the column type you’re using.</li> </ul> <p>In our <tt class="docutils literal"><span class="pre">HandField</span></tt> class, we’re storing the data as a VARCHAR field in the database, so we need to be able to process strings and <tt class="docutils literal"><span class="pre">Hand</span></tt> instances in <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">re</span> <span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">to_python</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">Hand</span><span class="p">):</span> <span class="k">return</span> <span class="n">value</span> <span class="c"># The string case.</span> <span class="n">p1</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">'.{26}'</span><span class="p">)</span> <span class="n">p2</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">'..'</span><span class="p">)</span> <span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="n">p2</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p1</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">value</span><span class="p">)]</span> <span class="k">return</span> <span class="n">Hand</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> </pre></div> </div> <p>Notice that we always return a <tt class="docutils literal"><span class="pre">Hand</span></tt> instance from this method. That’s the Python object type we want to store in the model’s attribute.</p> <p><strong>Remember:</strong> If your custom field needs the <tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt> method to be called when it is created, you should be using <a class="reference internal" href="#the-subfieldbase-metaclass">The SubfieldBase metaclass</a> mentioned earlier. Otherwise <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> won’t be called automatically.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">If your custom field allows <tt class="docutils literal"><span class="pre">null=True</span></tt>, any field method that takes <tt class="docutils literal"><span class="pre">value</span></tt> as an argument, like <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> and <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>, should handle the case when <tt class="docutils literal"><span class="pre">value</span></tt> is <tt class="docutils literal"><span class="pre">None</span></tt>.</p> </div> </div> <div class="section" id="s-converting-python-objects-to-query-values"> <span id="converting-python-objects-to-query-values"></span><h4>Converting Python objects to query values<a class="headerlink" href="#converting-python-objects-to-query-values" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.get_prep_value"> <tt class="descclassname">Field.</tt><tt class="descname">get_prep_value</tt>(<em>self</em>, <em>value</em>)<a class="headerlink" href="#django.db.models.Field.get_prep_value" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.2:</span> This method was factored out of <tt class="docutils literal"><span class="pre">get_db_prep_value()</span></tt></div> <p>This is the reverse of <a class="reference internal" href="#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> when working with the database backends (as opposed to serialization). The <tt class="docutils literal"><span class="pre">value</span></tt> parameter is the current value of the model’s attribute (a field has no reference to its containing model, so it cannot retrieve the value itself), and the method should return data in a format that has been prepared for use as a parameter in a query.</p> <p>This conversion should <em>not</em> include any database-specific conversions. If database-specific conversions are required, they should be made in the call to <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a>.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">get_prep_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="k">return</span> <span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="p">(</span><span class="n">value</span><span class="o">.</span><span class="n">north</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">east</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">south</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">west</span><span class="p">)])</span> </pre></div> </div> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">If your custom field uses the <tt class="docutils literal"><span class="pre">CHAR</span></tt>, <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> or <tt class="docutils literal"><span class="pre">TEXT</span></tt> types for MySQL, you must make sure that <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a> always returns a string type. MySQL performs flexible and unexpected matching when a query is performed on these types and the provided value is an integer, which can cause queries to include unexpected objects in their results. This problem cannot occur if you always return a string type from <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>.</p> </div> </div> <div class="section" id="s-converting-query-values-to-database-values"> <span id="converting-query-values-to-database-values"></span><h4>Converting query values to database values<a class="headerlink" href="#converting-query-values-to-database-values" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.get_db_prep_value"> <tt class="descclassname">Field.</tt><tt class="descname">get_db_prep_value</tt>(<em>self</em>, <em>value</em>, <em>connection</em>, <em>prepared=False</em>)<a class="headerlink" href="#django.db.models.Field.get_db_prep_value" 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">connection</span></tt> and <tt class="docutils literal"><span class="pre">prepared</span></tt> arguments were added to support multiple databases.</div> <p>Some data types (for example, dates) need to be in a specific format before they can be used by a database backend. <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a> is the method where those conversions should be made. The specific connection that will be used for the query is passed as the <tt class="docutils literal"><span class="pre">connection</span></tt> parameter. This allows you to use backend-specific conversion logic if it is required.</p> <p>The <tt class="docutils literal"><span class="pre">prepared</span></tt> argument describes whether or not the value has already been passed through <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a> conversions. When <tt class="docutils literal"><span class="pre">prepared</span></tt> is False, the default implementation of <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a> will call <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a> to do initial data conversions before performing any database-specific processing.</p> <dl class="method"> <dt id="django.db.models.Field.get_db_prep_save"> <tt class="descclassname">Field.</tt><tt class="descname">get_db_prep_save</tt>(<em>self</em>, <em>value</em>, <em>connection</em>)<a class="headerlink" href="#django.db.models.Field.get_db_prep_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">connection</span></tt> argument was added to support multiple databases.</div> <p>Same as the above, but called when the Field value must be <em>saved</em> to the database. As the default implementation just calls <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a>, you shouldn’t need to implement this method unless your custom field needs a special conversion when being saved that is not the same as the conversion used for normal query parameters (which is implemented by <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a>).</p> </div> <div class="section" id="s-preprocessing-values-before-saving"> <span id="preprocessing-values-before-saving"></span><h4>Preprocessing values before saving<a class="headerlink" href="#preprocessing-values-before-saving" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.pre_save"> <tt class="descclassname">Field.</tt><tt class="descname">pre_save</tt>(<em>self</em>, <em>model_instance</em>, <em>add</em>)<a class="headerlink" href="#django.db.models.Field.pre_save" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method is called just prior to <a class="reference internal" href="#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_save()</span></tt></a> and should return the value of the appropriate attribute from <tt class="docutils literal"><span class="pre">model_instance</span></tt> for this field. The attribute name is in <tt class="docutils literal"><span class="pre">self.attname</span></tt> (this is set up by <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>). If the model is being saved to the database for the first time, the <tt class="docutils literal"><span class="pre">add</span></tt> parameter will be <tt class="docutils literal"><span class="pre">True</span></tt>, otherwise it will be <tt class="docutils literal"><span class="pre">False</span></tt>.</p> <p>You only need to override this method if you want to preprocess the value somehow, just before saving. For example, Django’s <a class="reference internal" href="../ref/models/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> uses this method to set the attribute correctly in the case of <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> or <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now_add" title="django.db.models.DateField.auto_now_add"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now_add</span></tt></a>.</p> <p>If you do override this method, you must return the value of the attribute at the end. You should also update the model’s attribute if you make any changes to the value so that code holding references to the model will always see the correct value.</p> </div> <div class="section" id="s-preparing-values-for-use-in-database-lookups"> <span id="preparing-values-for-use-in-database-lookups"></span><h4>Preparing values for use in database lookups<a class="headerlink" href="#preparing-values-for-use-in-database-lookups" title="Permalink to this headline">¶</a></h4> <p>As with value conversions, preparing a value for database lookups is a two phase process.</p> <dl class="method"> <dt id="django.db.models.Field.get_prep_lookup"> <tt class="descclassname">Field.</tt><tt class="descname">get_prep_lookup</tt>(<em>self</em>, <em>lookup_type</em>, <em>value</em>)<a class="headerlink" href="#django.db.models.Field.get_prep_lookup" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="versionadded"> <span class="title">New in Django 1.2:</span> This method was factored out of <tt class="docutils literal"><span class="pre">get_db_prep_lookup()</span></tt></div> <p><a class="reference internal" href="#django.db.models.Field.get_prep_lookup" title="django.db.models.Field.get_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_lookup()</span></tt></a> performs the first phase of lookup preparation, performing generic data validity checks</p> <p>Prepares the <tt class="docutils literal"><span class="pre">value</span></tt> for passing to the database when used in a lookup (a <tt class="docutils literal"><span class="pre">WHERE</span></tt> constraint in SQL). The <tt class="docutils literal"><span class="pre">lookup_type</span></tt> will be one of the valid Django filter lookups: <tt class="docutils literal"><span class="pre">exact</span></tt>, <tt class="docutils literal"><span class="pre">iexact</span></tt>, <tt class="docutils literal"><span class="pre">contains</span></tt>, <tt class="docutils literal"><span class="pre">icontains</span></tt>, <tt class="docutils literal"><span class="pre">gt</span></tt>, <tt class="docutils literal"><span class="pre">gte</span></tt>, <tt class="docutils literal"><span class="pre">lt</span></tt>, <tt class="docutils literal"><span class="pre">lte</span></tt>, <tt class="docutils literal"><span class="pre">in</span></tt>, <tt class="docutils literal"><span class="pre">startswith</span></tt>, <tt class="docutils literal"><span class="pre">istartswith</span></tt>, <tt class="docutils literal"><span class="pre">endswith</span></tt>, <tt class="docutils literal"><span class="pre">iendswith</span></tt>, <tt class="docutils literal"><span class="pre">range</span></tt>, <tt class="docutils literal"><span class="pre">year</span></tt>, <tt class="docutils literal"><span class="pre">month</span></tt>, <tt class="docutils literal"><span class="pre">day</span></tt>, <tt class="docutils literal"><span class="pre">isnull</span></tt>, <tt class="docutils literal"><span class="pre">search</span></tt>, <tt class="docutils literal"><span class="pre">regex</span></tt>, and <tt class="docutils literal"><span class="pre">iregex</span></tt>.</p> <p>Your method must be prepared to handle all of these <tt class="docutils literal"><span class="pre">lookup_type</span></tt> values and should raise either a <tt class="docutils literal"><span class="pre">ValueError</span></tt> if the <tt class="docutils literal"><span class="pre">value</span></tt> is of the wrong sort (a list when you were expecting an object, for example) or a <tt class="docutils literal"><span class="pre">TypeError</span></tt> if your field does not support that type of lookup. For many fields, you can get by with handling the lookup types that need special handling for your field and pass the rest to the <a class="reference internal" href="#django.db.models.Field.get_db_prep_lookup" title="django.db.models.Field.get_db_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_lookup()</span></tt></a> method of the parent class.</p> <p>If you needed to implement <tt class="docutils literal"><span class="pre">get_db_prep_save()</span></tt>, you will usually need to implement <tt class="docutils literal"><span class="pre">get_prep_lookup()</span></tt>. If you don’t, <tt class="docutils literal"><span class="pre">get_prep_value</span></tt> will be called by the default implementation, to manage <tt class="docutils literal"><span class="pre">exact</span></tt>, <tt class="docutils literal"><span class="pre">gt</span></tt>, <tt class="docutils literal"><span class="pre">gte</span></tt>, <tt class="docutils literal"><span class="pre">lt</span></tt>, <tt class="docutils literal"><span class="pre">lte</span></tt>, <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">range</span></tt> lookups.</p> <p>You may also want to implement this method to limit the lookup types that could be used with your custom field type.</p> <p>Note that, for <tt class="docutils literal"><span class="pre">range</span></tt> and <tt class="docutils literal"><span class="pre">in</span></tt> lookups, <tt class="docutils literal"><span class="pre">get_prep_lookup</span></tt> will receive a list of objects (presumably of the right type) and will need to convert them to a list of things of the right type for passing to the database. Most of the time, you can reuse <tt class="docutils literal"><span class="pre">get_prep_value()</span></tt>, or at least factor out some common pieces.</p> <p>For example, the following code implements <tt class="docutils literal"><span class="pre">get_prep_lookup</span></tt> to limit the accepted lookup types to <tt class="docutils literal"><span class="pre">exact</span></tt> and <tt class="docutils literal"><span class="pre">in</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">get_prep_lookup</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">lookup_type</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="c"># We only handle 'exact' and 'in'. All others are errors.</span> <span class="k">if</span> <span class="n">lookup_type</span> <span class="o">==</span> <span class="s">'exact'</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="k">elif</span> <span class="n">lookup_type</span> <span class="o">==</span> <span class="s">'in'</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">get_prep_value</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">value</span><span class="p">]</span> <span class="k">else</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">'Lookup type </span><span class="si">%r</span><span class="s"> not supported.'</span> <span class="o">%</span> <span class="n">lookup_type</span><span class="p">)</span> </pre></div> </div> <dl class="method"> <dt id="django.db.models.Field.get_db_prep_lookup"> <tt class="descclassname">Field.</tt><tt class="descname">get_db_prep_lookup</tt>(<em>self</em>, <em>lookup_type</em>, <em>value</em>, <em>connection</em>, <em>prepared=False</em>)<a class="headerlink" href="#django.db.models.Field.get_db_prep_lookup" 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">connection</span></tt> and <tt class="docutils literal"><span class="pre">prepared</span></tt> arguments were added to support multiple databases.</div> <p>Performs any database-specific data conversions required by a lookup. As with <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a>, the specific connection that will be used for the query is passed as the <tt class="docutils literal"><span class="pre">connection</span></tt> parameter. The <tt class="docutils literal"><span class="pre">prepared</span></tt> argument describes whether the value has already been prepared with <a class="reference internal" href="#django.db.models.Field.get_prep_lookup" title="django.db.models.Field.get_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_lookup()</span></tt></a>.</p> </div> <div class="section" id="s-specifying-the-form-field-for-a-model-field"> <span id="specifying-the-form-field-for-a-model-field"></span><h4>Specifying the form field for a model field<a class="headerlink" href="#specifying-the-form-field-for-a-model-field" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.formfield"> <tt class="descclassname">Field.</tt><tt class="descname">formfield</tt>(<em>self</em>, <em>form_class=forms.CharField</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.Field.formfield" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Returns the default form field to use when this field is displayed in a model. This method is called by 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> helper.</p> <p>All of the <tt class="docutils literal"><span class="pre">kwargs</span></tt> dictionary is passed directly to the form field’s <tt class="xref py py-meth docutils literal"><span class="pre">Field__init__()</span></tt> method. Normally, all you need to do is set up a good default for the <tt class="docutils literal"><span class="pre">form_class</span></tt> argument and then delegate further handling to the parent class. This might require you to write a custom form field (and even a form widget). See the <a class="reference internal" href="../topics/forms/index.html"><em>forms documentation</em></a> for information about this, and take a look at the code in <a class="reference internal" href="../ref/contrib/localflavor.html#module-django.contrib.localflavor" title="django.contrib.localflavor: A collection of various Django snippets that are useful only for a particular country or culture."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.localflavor</span></tt></a> for some examples of custom widgets.</p> <p>Continuing our ongoing example, we can write the <a class="reference internal" href="#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><tt class="xref py py-meth docutils literal"><span class="pre">formfield()</span></tt></a> method as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">formfield</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="c"># This is a fairly standard way to set up some defaults</span> <span class="c"># while letting the caller override them.</span> <span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s">'form_class'</span><span class="p">:</span> <span class="n">MyFormField</span><span class="p">}</span> <span class="n">defaults</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span> <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">formfield</span><span class="p">(</span><span class="o">**</span><span class="n">defaults</span><span class="p">)</span> </pre></div> </div> <p>This assumes we’ve imported a <tt class="docutils literal"><span class="pre">MyFormField</span></tt> field class (which has its own default widget). This document doesn’t cover the details of writing custom form fields.</p> </div> <div class="section" id="s-emulating-built-in-field-types"> <span id="emulating-built-in-field-types"></span><h4>Emulating built-in field types<a class="headerlink" href="#emulating-built-in-field-types" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.get_internal_type"> <tt class="descclassname">Field.</tt><tt class="descname">get_internal_type</tt>(<em>self</em>)<a class="headerlink" href="#django.db.models.Field.get_internal_type" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Returns a string giving the name of the <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass we are emulating at the database level. This is used to determine the type of database column for simple cases.</p> <p>If you have created a <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method, you don’t need to worry about <a class="reference internal" href="#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><tt class="xref py py-meth docutils literal"><span class="pre">get_internal_type()</span></tt></a> – it won’t be used much. Sometimes, though, your database storage is similar in type to some other field, so you can use that other field’s logic to create the right column.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">get_internal_type</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">'CharField'</span> </pre></div> </div> <p>No matter which database backend we are using, this will mean that <tt class="docutils literal"><span class="pre">syncdb</span></tt> and other SQL commands create the right column type for storing a string.</p> <p>If <a class="reference internal" href="#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><tt class="xref py py-meth docutils literal"><span class="pre">get_internal_type()</span></tt></a> returns a string that is not known to Django for the database backend you are using – that is, it doesn’t appear in <tt class="docutils literal"><span class="pre">django.db.backends.<db_name>.creation.DATA_TYPES</span></tt> – the string will still be used by the serializer, but the default <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method will return <tt class="docutils literal"><span class="pre">None</span></tt>. See the documentation of <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> for reasons why this might be useful. Putting a descriptive string in as the type of the field for the serializer is a useful idea if you’re ever going to be using the serializer output in some other place, outside of Django.</p> </div> <div class="section" id="s-converting-field-data-for-serialization"> <span id="converting-field-data-for-serialization"></span><h4>Converting field data for serialization<a class="headerlink" href="#converting-field-data-for-serialization" title="Permalink to this headline">¶</a></h4> <dl class="method"> <dt id="django.db.models.Field.value_to_string"> <tt class="descclassname">Field.</tt><tt class="descname">value_to_string</tt>(<em>self</em>, <em>obj</em>)<a class="headerlink" href="#django.db.models.Field.value_to_string" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>This method is used by the serializers to convert the field into a string for output. Calling <tt class="xref py py-meth docutils literal"><span class="pre">Field._get_val_from_obj(obj)()</span></tt> is the best way to get the value to serialize. For example, since our <tt class="docutils literal"><span class="pre">HandField</span></tt> uses strings for its data storage anyway, we can reuse some existing conversion code:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span> <span class="c"># ...</span> <span class="k">def</span> <span class="nf">value_to_string</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="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_val_from_obj</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> </pre></div> </div> </div> </div> <div class="section" id="s-some-general-advice"> <span id="some-general-advice"></span><h3>Some general advice<a class="headerlink" href="#some-general-advice" title="Permalink to this headline">¶</a></h3> <p>Writing a custom field can be a tricky process, particularly if you’re doing complex conversions between your Python types and your database and serialization formats. Here are a couple of tips to make things go more smoothly:</p> <ol class="arabic simple"> <li>Look at the existing Django fields (in <tt class="file docutils literal"><span class="pre">django/db/models/fields/__init__.py</span></tt>) for inspiration. Try to find a field that’s similar to what you want and extend it a little bit, instead of creating an entirely new field from scratch.</li> <li>Put a <tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt> or <tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt> method on the class you’re wrapping up as a field. There are a lot of places where the default behavior of the field code is to call <a class="reference internal" href="../ref/utils.html#django.utils.encoding.force_unicode" title="django.utils.encoding.force_unicode"><tt class="xref py py-func docutils literal"><span class="pre">force_unicode()</span></tt></a> on the value. (In our examples in this document, <tt class="docutils literal"><span class="pre">value</span></tt> would be a <tt class="docutils literal"><span class="pre">Hand</span></tt> instance, not a <tt class="docutils literal"><span class="pre">HandField</span></tt>). So if your <tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt> method automatically converts to the string form of your Python object, you can save yourself a lot of work.</li> </ol> </div> </div> <div class="section" id="s-writing-a-filefield-subclass"> <span id="writing-a-filefield-subclass"></span><h2>Writing a <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass<a class="headerlink" href="#writing-a-filefield-subclass" title="Permalink to this headline">¶</a></h2> <p>In addition to the above methods, fields that deal with files have a few other special requirements which must be taken into account. The majority of the mechanics provided by <tt class="docutils literal"><span class="pre">FileField</span></tt>, such as controlling database storage and retrieval, can remain unchanged, leaving subclasses to deal with the challenge of supporting a particular type of file.</p> <p>Django provides a <tt class="docutils literal"><span class="pre">File</span></tt> class, which is used as a proxy to the file’s contents and operations. This can be subclassed to customize how the file is accessed, and what methods are available. It lives at <tt class="docutils literal"><span class="pre">django.db.models.fields.files</span></tt>, and its default behavior is explained in the <a class="reference internal" href="../ref/files/file.html"><em>file documentation</em></a>.</p> <p>Once a subclass of <tt class="docutils literal"><span class="pre">File</span></tt> is created, the new <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass must be told to use it. To do so, simply assign the new <tt class="docutils literal"><span class="pre">File</span></tt> subclass to the special <tt class="docutils literal"><span class="pre">attr_class</span></tt> attribute of the <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass.</p> <div class="section" id="s-a-few-suggestions"> <span id="a-few-suggestions"></span><h3>A few suggestions<a class="headerlink" href="#a-few-suggestions" title="Permalink to this headline">¶</a></h3> <p>In addition to the above details, there are a few guidelines which can greatly improve the efficiency and readability of the field’s code.</p> <ol class="arabic simple"> <li>The source for Django’s own <tt class="docutils literal"><span class="pre">ImageField</span></tt> (in <tt class="docutils literal"><span class="pre">django/db/models/fields/files.py</span></tt>) is a great example of how to subclass <tt class="docutils literal"><span class="pre">FileField</span></tt> to support a particular type of file, as it incorporates all of the techniques described above.</li> <li>Cache file attributes wherever possible. Since files may be stored in remote storage systems, retrieving them may cost extra time, or even money, that isn’t always necessary. Once a file is retrieved to obtain some data about its content, cache as much of that data as possible to reduce the number of times the file must be retrieved on subsequent calls for that information.</li> </ol> </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="#">Writing custom model fields</a><ul> <li><a class="reference internal" href="#introduction">Introduction</a><ul> <li><a class="reference internal" href="#our-example-object">Our example object</a></li> </ul> </li> <li><a class="reference internal" href="#background-theory">Background theory</a><ul> <li><a class="reference internal" href="#database-storage">Database storage</a></li> <li><a class="reference internal" href="#what-does-a-field-class-do">What does a field class do?</a></li> </ul> </li> <li><a class="reference internal" href="#writing-a-field-subclass">Writing a field subclass</a><ul> <li><a class="reference internal" href="#the-subfieldbase-metaclass">The <tt class="docutils literal"><span class="pre">SubfieldBase</span></tt> metaclass</a><ul> <li><a class="reference internal" href="#modelforms-and-custom-fields">ModelForms and custom fields</a></li> </ul> </li> <li><a class="reference internal" href="#documenting-your-custom-field">Documenting your custom field</a></li> <li><a class="reference internal" href="#useful-methods">Useful methods</a><ul> <li><a class="reference internal" href="#custom-database-types">Custom database types</a></li> <li><a class="reference internal" href="#converting-database-values-to-python-objects">Converting database values to Python objects</a></li> <li><a class="reference internal" href="#converting-python-objects-to-query-values">Converting Python objects to query values</a></li> <li><a class="reference internal" href="#converting-query-values-to-database-values">Converting query values to database values</a></li> <li><a class="reference internal" href="#preprocessing-values-before-saving">Preprocessing values before saving</a></li> <li><a class="reference internal" href="#preparing-values-for-use-in-database-lookups">Preparing values for use in database lookups</a></li> <li><a class="reference internal" href="#specifying-the-form-field-for-a-model-field">Specifying the form field for a model field</a></li> <li><a class="reference internal" href="#emulating-built-in-field-types">Emulating built-in field types</a></li> <li><a class="reference internal" href="#converting-field-data-for-serialization">Converting field data for serialization</a></li> </ul> </li> <li><a class="reference internal" href="#some-general-advice">Some general advice</a></li> </ul> </li> <li><a class="reference internal" href="#writing-a-filefield-subclass">Writing a <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass</a><ul> <li><a class="reference internal" href="#a-few-suggestions">A few suggestions</a></li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="custom-management-commands.html">Writing custom django-admin commands</a></li> <li>Next: <a href="custom-template-tags.html">Custom template tags and filters</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../index.html">Django 1.4.18 documentation</a> <ul><li><a href="index.html">“How-to” guides</a> <ul><li>Writing custom model fields</li></ul> </li></ul> </li> </ul> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/howto/custom-model-fields.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">Jan 15, 2015</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="custom-management-commands.html" title="Writing custom django-admin commands">previous</a> | <a href="index.html" title="&#8220;How-to&#8221; guides" accesskey="U">up</a> | <a href="custom-template-tags.html" title="Custom template tags and filters">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>