parts/django/docs/howto/custom-model-fields.txt
changeset 69 c6bca38c1cbf
equal deleted inserted replaced
68:5ff1fc726848 69:c6bca38c1cbf
       
     1 ===========================
       
     2 Writing custom model fields
       
     3 ===========================
       
     4 
       
     5 .. versionadded:: 1.0
       
     6 .. currentmodule:: django.db.models
       
     7 
       
     8 Introduction
       
     9 ============
       
    10 
       
    11 The :doc:`model reference </topics/db/models>` documentation explains how to use
       
    12 Django's standard field classes -- :class:`~django.db.models.CharField`,
       
    13 :class:`~django.db.models.DateField`, etc. For many purposes, those classes are
       
    14 all you'll need. Sometimes, though, the Django version won't meet your precise
       
    15 requirements, or you'll want to use a field that is entirely different from
       
    16 those shipped with Django.
       
    17 
       
    18 Django's built-in field types don't cover every possible database column type --
       
    19 only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
       
    20 column types, such as geographic polygons or even user-created types such as
       
    21 `PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.
       
    22 
       
    23 .. _PostgreSQL custom types: http://www.postgresql.org/docs/8.2/interactive/sql-createtype.html
       
    24 
       
    25 Alternatively, you may have a complex Python object that can somehow be
       
    26 serialized to fit into a standard database column type. This is another case
       
    27 where a ``Field`` subclass will help you use your object with your models.
       
    28 
       
    29 Our example object
       
    30 ------------------
       
    31 
       
    32 Creating custom fields requires a bit of attention to detail. To make things
       
    33 easier to follow, we'll use a consistent example throughout this document:
       
    34 wrapping a Python object representing the deal of cards in a hand of Bridge_.
       
    35 Don't worry, you don't have know how to play Bridge to follow this example.
       
    36 You only need to know that 52 cards are dealt out equally to four players, who
       
    37 are traditionally called *north*, *east*, *south* and *west*.  Our class looks
       
    38 something like this::
       
    39 
       
    40     class Hand(object):
       
    41         """A hand of cards (bridge style)"""
       
    42 
       
    43         def __init__(self, north, east, south, west):
       
    44             # Input parameters are lists of cards ('Ah', '9s', etc)
       
    45             self.north = north
       
    46             self.east = east
       
    47             self.south = south
       
    48             self.west = west
       
    49 
       
    50         # ... (other possibly useful methods omitted) ...
       
    51 
       
    52 .. _Bridge: http://en.wikipedia.org/wiki/Contract_bridge
       
    53 
       
    54 This is just an ordinary Python class, with nothing Django-specific about it.
       
    55 We'd like to be able to do things like this in our models (we assume the
       
    56 ``hand`` attribute on the model is an instance of ``Hand``)::
       
    57 
       
    58     example = MyModel.objects.get(pk=1)
       
    59     print example.hand.north
       
    60 
       
    61     new_hand = Hand(north, east, south, west)
       
    62     example.hand = new_hand
       
    63     example.save()
       
    64 
       
    65 We assign to and retrieve from the ``hand`` attribute in our model just like
       
    66 any other Python class. The trick is to tell Django how to handle saving and
       
    67 loading such an object.
       
    68 
       
    69 In order to use the ``Hand`` class in our models, we **do not** have to change
       
    70 this class at all. This is ideal, because it means you can easily write
       
    71 model support for existing classes where you cannot change the source code.
       
    72 
       
    73 .. note::
       
    74     You might only be wanting to take advantage of custom database column
       
    75     types and deal with the data as standard Python types in your models;
       
    76     strings, or floats, for example. This case is similar to our ``Hand``
       
    77     example and we'll note any differences as we go along.
       
    78 
       
    79 Background theory
       
    80 =================
       
    81 
       
    82 Database storage
       
    83 ----------------
       
    84 
       
    85 The simplest way to think of a model field is that it provides a way to take a
       
    86 normal Python object -- string, boolean, ``datetime``, or something more
       
    87 complex like ``Hand`` -- and convert it to and from a format that is useful
       
    88 when dealing with the database (and serialization, but, as we'll see later,
       
    89 that falls out fairly naturally once you have the database side under control).
       
    90 
       
    91 Fields in a model must somehow be converted to fit into an existing database
       
    92 column type. Different databases provide different sets of valid column types,
       
    93 but the rule is still the same: those are the only types you have to work
       
    94 with. Anything you want to store in the database must fit into one of
       
    95 those types.
       
    96 
       
    97 Normally, you're either writing a Django field to match a particular database
       
    98 column type, or there's a fairly straightforward way to convert your data to,
       
    99 say, a string.
       
   100 
       
   101 For our ``Hand`` example, we could convert the card data to a string of 104
       
   102 characters by concatenating all the cards together in a pre-determined order --
       
   103 say, all the *north* cards first, then the *east*, *south* and *west* cards. So
       
   104 ``Hand`` objects can be saved to text or character columns in the database.
       
   105 
       
   106 What does a field class do?
       
   107 ---------------------------
       
   108 
       
   109 All of Django's fields (and when we say *fields* in this document, we always
       
   110 mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
       
   111 of :class:`django.db.models.Field`. Most of the information that Django records
       
   112 about a field is common to all fields -- name, help text, uniqueness and so
       
   113 forth. Storing all that information is handled by ``Field``. We'll get into the
       
   114 precise details of what ``Field`` can do later on; for now, suffice it to say
       
   115 that everything descends from ``Field`` and then customizes key pieces of the
       
   116 class behavior.
       
   117 
       
   118 It's important to realize that a Django field class is not what is stored in
       
   119 your model attributes. The model attributes contain normal Python objects. The
       
   120 field classes you define in a model are actually stored in the ``Meta`` class
       
   121 when the model class is created (the precise details of how this is done are
       
   122 unimportant here). This is because the field classes aren't necessary when
       
   123 you're just creating and modifying attributes. Instead, they provide the
       
   124 machinery for converting between the attribute value and what is stored in the
       
   125 database or sent to the :doc:`serializer </topics/serialization>`.
       
   126 
       
   127 Keep this in mind when creating your own custom fields. The Django ``Field``
       
   128 subclass you write provides the machinery for converting between your Python
       
   129 instances and the database/serializer values in various ways (there are
       
   130 differences between storing a value and using a value for lookups, for
       
   131 example). If this sounds a bit tricky, don't worry -- it will become clearer in
       
   132 the examples below. Just remember that you will often end up creating two
       
   133 classes when you want a custom field:
       
   134 
       
   135     * The first class is the Python object that your users will manipulate.
       
   136       They will assign it to the model attribute, they will read from it for
       
   137       displaying purposes, things like that. This is the ``Hand`` class in our
       
   138       example.
       
   139 
       
   140     * The second class is the ``Field`` subclass. This is the class that knows
       
   141       how to convert your first class back and forth between its permanent
       
   142       storage form and the Python form.
       
   143 
       
   144 Writing a field subclass
       
   145 ========================
       
   146 
       
   147 When planning your :class:`~django.db.models.Field` subclass, first give some
       
   148 thought to which existing :class:`~django.db.models.Field` class your new field
       
   149 is most similar to. Can you subclass an existing Django field and save yourself
       
   150 some work? If not, you should subclass the :class:`~django.db.models.Field`
       
   151 class, from which everything is descended.
       
   152 
       
   153 Initializing your new field is a matter of separating out any arguments that are
       
   154 specific to your case from the common arguments and passing the latter to the
       
   155 :meth:`~django.db.models.Field.__init__` method of
       
   156 :class:`~django.db.models.Field` (or your parent class).
       
   157 
       
   158 In our example, we'll call our field ``HandField``. (It's a good idea to call
       
   159 your :class:`~django.db.models.Field` subclass ``<Something>Field``, so it's
       
   160 easily identifiable as a :class:`~django.db.models.Field` subclass.) It doesn't
       
   161 behave like any existing field, so we'll subclass directly from
       
   162 :class:`~django.db.models.Field`::
       
   163 
       
   164     from django.db import models
       
   165 
       
   166     class HandField(models.Field):
       
   167 
       
   168         description = "A hand of cards (bridge style)"
       
   169 
       
   170         def __init__(self, *args, **kwargs):
       
   171             kwargs['max_length'] = 104
       
   172             super(HandField, self).__init__(*args, **kwargs)
       
   173 
       
   174 Our ``HandField`` accepts most of the standard field options (see the list
       
   175 below), but we ensure it has a fixed length, since it only needs to hold 52
       
   176 card values plus their suits; 104 characters in total.
       
   177 
       
   178 .. note::
       
   179     Many of Django's model fields accept options that they don't do anything
       
   180     with. For example, you can pass both
       
   181     :attr:`~django.db.models.Field.editable` and
       
   182     :attr:`~django.db.models.Field.auto_now` to a
       
   183     :class:`django.db.models.DateField` and it will simply ignore the
       
   184     :attr:`~django.db.models.Field.editable` parameter
       
   185     (:attr:`~django.db.models.Field.auto_now` being set implies
       
   186     ``editable=False``). No error is raised in this case.
       
   187 
       
   188     This behavior simplifies the field classes, because they don't need to
       
   189     check for options that aren't necessary. They just pass all the options to
       
   190     the parent class and then don't use them later on. It's up to you whether
       
   191     you want your fields to be more strict about the options they select, or
       
   192     to use the simpler, more permissive behavior of the current fields.
       
   193 
       
   194 The :meth:`~django.db.models.Field.__init__` method takes the following
       
   195 parameters:
       
   196 
       
   197     * :attr:`~django.db.models.Field.verbose_name`
       
   198     * :attr:`~django.db.models.Field.name`
       
   199     * :attr:`~django.db.models.Field.primary_key`
       
   200     * :attr:`~django.db.models.Field.max_length`
       
   201     * :attr:`~django.db.models.Field.unique`
       
   202     * :attr:`~django.db.models.Field.blank`
       
   203     * :attr:`~django.db.models.Field.null`
       
   204     * :attr:`~django.db.models.Field.db_index`
       
   205     * :attr:`~django.db.models.Field.rel`: Used for related fields (like
       
   206       :class:`ForeignKey`). For advanced use only.
       
   207     * :attr:`~django.db.models.Field.default`
       
   208     * :attr:`~django.db.models.Field.editable`
       
   209     * :attr:`~django.db.models.Field.serialize`: If ``False``, the field will
       
   210       not be serialized when the model is passed to Django's :doc:`serializers
       
   211       </topics/serialization>`. Defaults to ``True``.
       
   212     * :attr:`~django.db.models.Field.unique_for_date`
       
   213     * :attr:`~django.db.models.Field.unique_for_month`
       
   214     * :attr:`~django.db.models.Field.unique_for_year`
       
   215     * :attr:`~django.db.models.Field.choices`
       
   216     * :attr:`~django.db.models.Field.help_text`
       
   217     * :attr:`~django.db.models.Field.db_column`
       
   218     * :attr:`~django.db.models.Field.db_tablespace`: Currently only used with
       
   219       the Oracle backend and only for index creation. You can usually ignore
       
   220       this option.
       
   221     * :attr:`~django.db.models.Field.auto_created`: True if the field was
       
   222       automatically created, as for the `OneToOneField` used by model
       
   223       inheritance. For advanced use only.
       
   224 
       
   225 All of the options without an explanation in the above list have the same
       
   226 meaning they do for normal Django fields. See the :doc:`field documentation
       
   227 </ref/models/fields>` for examples and details.
       
   228 
       
   229 The ``SubfieldBase`` metaclass
       
   230 ------------------------------
       
   231 
       
   232 As we indicated in the introduction_, field subclasses are often needed for
       
   233 two reasons: either to take advantage of a custom database column type, or to
       
   234 handle complex Python types. Obviously, a combination of the two is also
       
   235 possible. If you're only working with custom database column types and your
       
   236 model fields appear in Python as standard Python types direct from the
       
   237 database backend, you don't need to worry about this section.
       
   238 
       
   239 If you're handling custom Python types, such as our ``Hand`` class, we need to
       
   240 make sure that when Django initializes an instance of our model and assigns a
       
   241 database value to our custom field attribute, we convert that value into the
       
   242 appropriate Python object. The details of how this happens internally are a
       
   243 little complex, but the code you need to write in your ``Field`` class is
       
   244 simple: make sure your field subclass uses a special metaclass:
       
   245 
       
   246 .. class:: django.db.models.SubfieldBase
       
   247 
       
   248 For example::
       
   249 
       
   250     class HandField(models.Field):
       
   251 
       
   252         description = "A hand of cards (bridge style)"
       
   253 
       
   254         __metaclass__ = models.SubfieldBase
       
   255 
       
   256         def __init__(self, *args, **kwargs):
       
   257             # ...
       
   258 
       
   259 This ensures that the :meth:`to_python` method, documented below, will always be
       
   260 called when the attribute is initialized.
       
   261 
       
   262 ModelForms and custom fields
       
   263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   264 
       
   265 If you use :class:`~django.db.models.SubfieldBase`, :meth:`to_python`
       
   266 will be called every time an instance of the field is assigned a
       
   267 value. This means that whenever a value may be assigned to the field,
       
   268 you need to ensure that it will be of the correct datatype, or that
       
   269 you handle any exceptions.
       
   270 
       
   271 This is especially important if you use :doc:`ModelForms
       
   272 </topics/forms/modelforms>`. When saving a ModelForm, Django will use
       
   273 form values to instantiate model instances. However, if the cleaned
       
   274 form data can't be used as valid input to the field, the normal form
       
   275 validation process will break.
       
   276 
       
   277 Therefore, you must ensure that the form field used to represent your
       
   278 custom field performs whatever input validation and data cleaning is
       
   279 necessary to convert user-provided form input into a
       
   280 `to_python()`-compatible model field value. This may require writing a
       
   281 custom form field, and/or implementing the :meth:`formfield` method on
       
   282 your field to return a form field class whose `to_python()` returns the
       
   283 correct datatype.
       
   284 
       
   285 Documenting your Custom Field
       
   286 -----------------------------
       
   287 
       
   288 .. class:: django.db.models.Field
       
   289 
       
   290 .. attribute:: description
       
   291 
       
   292 As always, you should document your field type, so users will know what it is.
       
   293 In addition to providing a docstring for it, which is useful for developers,
       
   294 you can also allow users of the admin app to see a short description of the
       
   295 field type via the :doc:`django.contrib.admindocs
       
   296 </ref/contrib/admin/admindocs>` application. To do this simply provide
       
   297 descriptive text in a ``description`` class attribute of your custom field. In
       
   298 the above example, the type description displayed by the ``admindocs``
       
   299 application for a ``HandField`` will be 'A hand of cards (bridge style)'.
       
   300 
       
   301 Useful methods
       
   302 --------------
       
   303 
       
   304 Once you've created your :class:`~django.db.models.Field` subclass and set up
       
   305 the ``__metaclass__``, you might consider overriding a few standard methods,
       
   306 depending on your field's behavior. The list of methods below is in
       
   307 approximately decreasing order of importance, so start from the top.
       
   308 
       
   309 Custom database types
       
   310 ~~~~~~~~~~~~~~~~~~~~~
       
   311 
       
   312 .. method:: db_type(self, connection)
       
   313 
       
   314 .. versionadded:: 1.2
       
   315    The ``connection`` argument was added to support multiple databases.
       
   316 
       
   317 Returns the database column data type for the :class:`~django.db.models.Field`,
       
   318 taking into account the connection object, and the settings associated with it.
       
   319 
       
   320 Say you've created a PostgreSQL custom type called ``mytype``. You can use this
       
   321 field with Django by subclassing ``Field`` and implementing the :meth:`db_type`
       
   322 method, like so::
       
   323 
       
   324     from django.db import models
       
   325 
       
   326     class MytypeField(models.Field):
       
   327         def db_type(self, connection):
       
   328             return 'mytype'
       
   329 
       
   330 Once you have ``MytypeField``, you can use it in any model, just like any other
       
   331 ``Field`` type::
       
   332 
       
   333     class Person(models.Model):
       
   334         name = models.CharField(max_length=80)
       
   335         gender = models.CharField(max_length=1)
       
   336         something_else = MytypeField()
       
   337 
       
   338 If you aim to build a database-agnostic application, you should account for
       
   339 differences in database column types. For example, the date/time column type
       
   340 in PostgreSQL is called ``timestamp``, while the same column in MySQL is called
       
   341 ``datetime``. The simplest way to handle this in a ``db_type()`` method is to
       
   342 check the ``connection.settings_dict['ENGINE']`` attribute.
       
   343 
       
   344 For example::
       
   345 
       
   346     class MyDateField(models.Field):
       
   347         def db_type(self, connection):
       
   348             if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
       
   349                 return 'datetime'
       
   350             else:
       
   351                 return 'timestamp'
       
   352 
       
   353 The :meth:`db_type` method is only called by Django when the framework
       
   354 constructs the ``CREATE TABLE`` statements for your application -- that is, when
       
   355 you first create your tables. It's not called at any other time, so it can
       
   356 afford to execute slightly complex code, such as the ``connection.settings_dict``
       
   357 check in the above example.
       
   358 
       
   359 Some database column types accept parameters, such as ``CHAR(25)``, where the
       
   360 parameter ``25`` represents the maximum column length. In cases like these,
       
   361 it's more flexible if the parameter is specified in the model rather than being
       
   362 hard-coded in the ``db_type()`` method. For example, it wouldn't make much
       
   363 sense to have a ``CharMaxlength25Field``, shown here::
       
   364 
       
   365     # This is a silly example of hard-coded parameters.
       
   366     class CharMaxlength25Field(models.Field):
       
   367         def db_type(self, connection):
       
   368             return 'char(25)'
       
   369 
       
   370     # In the model:
       
   371     class MyModel(models.Model):
       
   372         # ...
       
   373         my_field = CharMaxlength25Field()
       
   374 
       
   375 The better way of doing this would be to make the parameter specifiable at run
       
   376 time -- i.e., when the class is instantiated. To do that, just implement
       
   377 :meth:`django.db.models.Field.__init__`, like so::
       
   378 
       
   379     # This is a much more flexible example.
       
   380     class BetterCharField(models.Field):
       
   381         def __init__(self, max_length, *args, **kwargs):
       
   382             self.max_length = max_length
       
   383             super(BetterCharField, self).__init__(*args, **kwargs)
       
   384 
       
   385         def db_type(self, connection):
       
   386             return 'char(%s)' % self.max_length
       
   387 
       
   388     # In the model:
       
   389     class MyModel(models.Model):
       
   390         # ...
       
   391         my_field = BetterCharField(25)
       
   392 
       
   393 Finally, if your column requires truly complex SQL setup, return ``None`` from
       
   394 :meth:`db_type`. This will cause Django's SQL creation code to skip over this
       
   395 field. You are then responsible for creating the column in the right table in
       
   396 some other way, of course, but this gives you a way to tell Django to get out of
       
   397 the way.
       
   398 
       
   399 Converting database values to Python objects
       
   400 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   401 
       
   402 .. method:: to_python(self, value)
       
   403 
       
   404 Converts a value as returned by your database (or a serializer) to a Python
       
   405 object.
       
   406 
       
   407 The default implementation simply returns ``value``, for the common case in
       
   408 which the database backend already returns data in the correct format (as a
       
   409 Python string, for example).
       
   410 
       
   411 If your custom :class:`~django.db.models.Field` class deals with data structures
       
   412 that are more complex than strings, dates, integers or floats, then you'll need
       
   413 to override this method. As a general rule, the method should deal gracefully
       
   414 with any of the following arguments:
       
   415 
       
   416     * An instance of the correct type (e.g., ``Hand`` in our ongoing example).
       
   417 
       
   418     * A string (e.g., from a deserializer).
       
   419 
       
   420     * Whatever the database returns for the column type you're using.
       
   421 
       
   422 In our ``HandField`` class, we're storing the data as a VARCHAR field in the
       
   423 database, so we need to be able to process strings and ``Hand`` instances in
       
   424 :meth:`to_python`::
       
   425 
       
   426     import re
       
   427 
       
   428     class HandField(models.Field):
       
   429         # ...
       
   430 
       
   431         def to_python(self, value):
       
   432             if isinstance(value, Hand):
       
   433                 return value
       
   434 
       
   435             # The string case.
       
   436             p1 = re.compile('.{26}')
       
   437             p2 = re.compile('..')
       
   438             args = [p2.findall(x) for x in p1.findall(value)]
       
   439             return Hand(*args)
       
   440 
       
   441 Notice that we always return a ``Hand`` instance from this method. That's the
       
   442 Python object type we want to store in the model's attribute.
       
   443 
       
   444 **Remember:** If your custom field needs the :meth:`to_python` method to be
       
   445 called when it is created, you should be using `The SubfieldBase metaclass`_
       
   446 mentioned earlier. Otherwise :meth:`to_python` won't be called automatically.
       
   447 
       
   448 Converting Python objects to query values
       
   449 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   450 
       
   451 .. method:: get_prep_value(self, value)
       
   452 
       
   453 .. versionadded:: 1.2
       
   454    This method was factored out of ``get_db_prep_value()``
       
   455 
       
   456 This is the reverse of :meth:`to_python` when working with the
       
   457 database backends (as opposed to serialization). The ``value``
       
   458 parameter is the current value of the model's attribute (a field has
       
   459 no reference to its containing model, so it cannot retrieve the value
       
   460 itself), and the method should return data in a format that has been
       
   461 prepared for use as a parameter in a query.
       
   462 
       
   463 This conversion should *not* include any database-specific
       
   464 conversions. If database-specific conversions are required, they
       
   465 should be made in the call to :meth:`get_db_prep_value`.
       
   466 
       
   467 For example::
       
   468 
       
   469     class HandField(models.Field):
       
   470         # ...
       
   471 
       
   472         def get_prep_value(self, value):
       
   473             return ''.join([''.join(l) for l in (value.north,
       
   474                     value.east, value.south, value.west)])
       
   475 
       
   476 Converting query values to database values
       
   477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   478 
       
   479 .. method:: get_db_prep_value(self, value, connection, prepared=False)
       
   480 
       
   481 .. versionadded:: 1.2
       
   482    The ``connection`` and ``prepared`` arguments were added to support multiple databases.
       
   483 
       
   484 Some data types (for example, dates) need to be in a specific format
       
   485 before they can be used by a database backend.
       
   486 :meth:`get_db_prep_value` is the method where those conversions should
       
   487 be made. The specific connection that will be used for the query is
       
   488 passed as the ``connection`` parameter. This allows you to use
       
   489 backend-specific conversion logic if it is required.
       
   490 
       
   491 The ``prepared`` argument describes whether or not the value has
       
   492 already been passed through :meth:`get_prep_value` conversions. When
       
   493 ``prepared`` is False, the default implementation of
       
   494 :meth:`get_db_prep_value` will call :meth:`get_prep_value` to do
       
   495 initial data conversions before performing any database-specific
       
   496 processing.
       
   497 
       
   498 .. method:: get_db_prep_save(self, value, connection)
       
   499 
       
   500 .. versionadded:: 1.2
       
   501    The ``connection`` argument was added to support multiple databases.
       
   502 
       
   503 Same as the above, but called when the Field value must be *saved* to
       
   504 the database. As the default implementation just calls
       
   505 ``get_db_prep_value``, you shouldn't need to implement this method
       
   506 unless your custom field needs a special conversion when being saved
       
   507 that is not the same as the conversion used for normal query
       
   508 parameters (which is implemented by ``get_db_prep_value``).
       
   509 
       
   510 Preprocessing values before saving
       
   511 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   512 
       
   513 .. method:: pre_save(self, model_instance, add)
       
   514 
       
   515 This method is called just prior to :meth:`get_db_prep_save` and should return
       
   516 the value of the appropriate attribute from ``model_instance`` for this field.
       
   517 The attribute name is in ``self.attname`` (this is set up by
       
   518 :class:`~django.db.models.Field`). If the model is being saved to the database
       
   519 for the first time, the ``add`` parameter will be ``True``, otherwise it will be
       
   520 ``False``.
       
   521 
       
   522 You only need to override this method if you want to preprocess the value
       
   523 somehow, just before saving. For example, Django's
       
   524 :class:`~django.db.models.DateTimeField` uses this method to set the attribute
       
   525 correctly in the case of :attr:`~django.db.models.Field.auto_now` or
       
   526 :attr:`~django.db.models.Field.auto_now_add`.
       
   527 
       
   528 If you do override this method, you must return the value of the attribute at
       
   529 the end. You should also update the model's attribute if you make any changes
       
   530 to the value so that code holding references to the model will always see the
       
   531 correct value.
       
   532 
       
   533 Preparing values for use in database lookups
       
   534 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   535 
       
   536 As with value conversions, preparing a value for database lookups is a
       
   537 two phase process.
       
   538 
       
   539 .. method:: get_prep_lookup(self, lookup_type, value)
       
   540 
       
   541 .. versionadded:: 1.2
       
   542    This method was factored out of ``get_db_prep_lookup()``
       
   543 
       
   544 :meth:`get_prep_lookup` performs the first phase of lookup preparation,
       
   545 performing generic data validity checks
       
   546 
       
   547 Prepares the ``value`` for passing to the database when used in a lookup (a
       
   548 ``WHERE`` constraint in SQL). The ``lookup_type`` will be one of the valid
       
   549 Django filter lookups: ``exact``, ``iexact``, ``contains``, ``icontains``,
       
   550 ``gt``, ``gte``, ``lt``, ``lte``, ``in``, ``startswith``, ``istartswith``,
       
   551 ``endswith``, ``iendswith``, ``range``, ``year``, ``month``, ``day``,
       
   552 ``isnull``, ``search``, ``regex``, and ``iregex``.
       
   553 
       
   554 Your method must be prepared to handle all of these ``lookup_type`` values and
       
   555 should raise either a ``ValueError`` if the ``value`` is of the wrong sort (a
       
   556 list when you were expecting an object, for example) or a ``TypeError`` if
       
   557 your field does not support that type of lookup. For many fields, you can get
       
   558 by with handling the lookup types that need special handling for your field
       
   559 and pass the rest to the :meth:`get_db_prep_lookup` method of the parent class.
       
   560 
       
   561 If you needed to implement ``get_db_prep_save()``, you will usually need to
       
   562 implement ``get_prep_lookup()``. If you don't, ``get_prep_value`` will be
       
   563 called by the default implementation, to manage ``exact``, ``gt``, ``gte``,
       
   564 ``lt``, ``lte``, ``in`` and ``range`` lookups.
       
   565 
       
   566 You may also want to implement this method to limit the lookup types that could
       
   567 be used with your custom field type.
       
   568 
       
   569 Note that, for ``range`` and ``in`` lookups, ``get_prep_lookup`` will receive
       
   570 a list of objects (presumably of the right type) and will need to convert them
       
   571 to a list of things of the right type for passing to the database. Most of the
       
   572 time, you can reuse ``get_prep_value()``, or at least factor out some common
       
   573 pieces.
       
   574 
       
   575 For example, the following code implements ``get_prep_lookup`` to limit the
       
   576 accepted lookup types to ``exact`` and ``in``::
       
   577 
       
   578     class HandField(models.Field):
       
   579         # ...
       
   580 
       
   581         def get_prep_lookup(self, lookup_type, value):
       
   582             # We only handle 'exact' and 'in'. All others are errors.
       
   583             if lookup_type == 'exact':
       
   584                 return self.get_prep_value(value)
       
   585             elif lookup_type == 'in':
       
   586                 return [self.get_prep_value(v) for v in value]
       
   587             else:
       
   588                 raise TypeError('Lookup type %r not supported.' % lookup_type)
       
   589 
       
   590 .. method:: get_db_prep_lookup(self, lookup_type, value, connection, prepared=False)
       
   591 
       
   592 .. versionadded:: 1.2
       
   593    The ``connection`` and ``prepared`` arguments were added to support multiple databases.
       
   594 
       
   595 Performs any database-specific data conversions required by a lookup.
       
   596 As with :meth:`get_db_prep_value`, the specific connection that will
       
   597 be used for the query is passed as the ``connection`` parameter.
       
   598 The ``prepared`` argument describes whether the value has already been
       
   599 prepared with :meth:`get_prep_lookup`.
       
   600 
       
   601 Specifying the form field for a model field
       
   602 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   603 
       
   604 .. method:: formfield(self, form_class=forms.CharField, **kwargs)
       
   605 
       
   606 Returns the default form field to use when this field is displayed in a model.
       
   607 This method is called by the :class:`~django.forms.ModelForm` helper.
       
   608 
       
   609 All of the ``kwargs`` dictionary is passed directly to the form field's
       
   610 :meth:`~django.forms.Field__init__` method. Normally, all you need to do is
       
   611 set up a good default for the ``form_class`` argument and then delegate further
       
   612 handling to the parent class. This might require you to write a custom form
       
   613 field (and even a form widget). See the :doc:`forms documentation
       
   614 </topics/forms/index>` for information about this, and take a look at the code in
       
   615 :mod:`django.contrib.localflavor` for some examples of custom widgets.
       
   616 
       
   617 Continuing our ongoing example, we can write the :meth:`formfield` method as::
       
   618 
       
   619     class HandField(models.Field):
       
   620         # ...
       
   621 
       
   622         def formfield(self, **kwargs):
       
   623             # This is a fairly standard way to set up some defaults
       
   624             # while letting the caller override them.
       
   625             defaults = {'form_class': MyFormField}
       
   626             defaults.update(kwargs)
       
   627             return super(HandField, self).formfield(**defaults)
       
   628 
       
   629 This assumes we've imported a ``MyFormField`` field class (which has its own
       
   630 default widget). This document doesn't cover the details of writing custom form
       
   631 fields.
       
   632 
       
   633 .. _helper functions: ../forms/#generating-forms-for-models
       
   634 .. _forms documentation: ../forms/
       
   635 
       
   636 Emulating built-in field types
       
   637 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   638 
       
   639 .. method:: get_internal_type(self)
       
   640 
       
   641 Returns a string giving the name of the :class:`~django.db.models.Field`
       
   642 subclass we are emulating at the database level. This is used to determine the
       
   643 type of database column for simple cases.
       
   644 
       
   645 If you have created a :meth:`db_type` method, you don't need to worry about
       
   646 :meth:`get_internal_type` -- it won't be used much. Sometimes, though, your
       
   647 database storage is similar in type to some other field, so you can use that
       
   648 other field's logic to create the right column.
       
   649 
       
   650 For example::
       
   651 
       
   652     class HandField(models.Field):
       
   653         # ...
       
   654 
       
   655         def get_internal_type(self):
       
   656             return 'CharField'
       
   657 
       
   658 No matter which database backend we are using, this will mean that ``syncdb``
       
   659 and other SQL commands create the right column type for storing a string.
       
   660 
       
   661 If :meth:`get_internal_type` returns a string that is not known to Django for
       
   662 the database backend you are using -- that is, it doesn't appear in
       
   663 ``django.db.backends.<db_name>.creation.DATA_TYPES`` -- the string will still be
       
   664 used by the serializer, but the default :meth:`db_type` method will return
       
   665 ``None``. See the documentation of :meth:`db_type` for reasons why this might be
       
   666 useful. Putting a descriptive string in as the type of the field for the
       
   667 serializer is a useful idea if you're ever going to be using the serializer
       
   668 output in some other place, outside of Django.
       
   669 
       
   670 Converting field data for serialization
       
   671 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   672 
       
   673 .. method:: value_to_string(self, obj)
       
   674 
       
   675 This method is used by the serializers to convert the field into a string for
       
   676 output. Calling :meth:`Field._get_val_from_obj(obj)` is the best way to get the
       
   677 value to serialize. For example, since our ``HandField`` uses strings for its
       
   678 data storage anyway, we can reuse some existing conversion code::
       
   679 
       
   680     class HandField(models.Field):
       
   681         # ...
       
   682 
       
   683         def value_to_string(self, obj):
       
   684             value = self._get_val_from_obj(obj)
       
   685             return self.get_db_prep_value(value)
       
   686 
       
   687 Some general advice
       
   688 --------------------
       
   689 
       
   690 Writing a custom field can be a tricky process, particularly if you're doing
       
   691 complex conversions between your Python types and your database and
       
   692 serialization formats. Here are a couple of tips to make things go more
       
   693 smoothly:
       
   694 
       
   695     1. Look at the existing Django fields (in
       
   696        :file:`django/db/models/fields/__init__.py`) for inspiration. Try to find
       
   697        a field that's similar to what you want and extend it a little bit,
       
   698        instead of creating an entirely new field from scratch.
       
   699 
       
   700     2. Put a :meth:`__str__` or :meth:`__unicode__` method on the class you're
       
   701        wrapping up as a field. There are a lot of places where the default
       
   702        behavior of the field code is to call
       
   703        :func:`~django.utils.encoding.force_unicode` on the value. (In our
       
   704        examples in this document, ``value`` would be a ``Hand`` instance, not a
       
   705        ``HandField``). So if your :meth:`__unicode__` method automatically
       
   706        converts to the string form of your Python object, you can save yourself
       
   707        a lot of work.
       
   708 
       
   709 
       
   710 Writing a ``FileField`` subclass
       
   711 =================================
       
   712 
       
   713 In addition to the above methods, fields that deal with files have a few other
       
   714 special requirements which must be taken into account. The majority of the
       
   715 mechanics provided by ``FileField``, such as controlling database storage and
       
   716 retrieval, can remain unchanged, leaving subclasses to deal with the challenge
       
   717 of supporting a particular type of file.
       
   718 
       
   719 Django provides a ``File`` class, which is used as a proxy to the file's
       
   720 contents and operations. This can be subclassed to customize how the file is
       
   721 accessed, and what methods are available. It lives at
       
   722 ``django.db.models.fields.files``, and its default behavior is explained in the
       
   723 :doc:`file documentation </ref/files/file>`.
       
   724 
       
   725 Once a subclass of ``File`` is created, the new ``FileField`` subclass must be
       
   726 told to use it. To do so, simply assign the new ``File`` subclass to the special
       
   727 ``attr_class`` attribute of the ``FileField`` subclass.
       
   728 
       
   729 A few suggestions
       
   730 ------------------
       
   731 
       
   732 In addition to the above details, there are a few guidelines which can greatly
       
   733 improve the efficiency and readability of the field's code.
       
   734 
       
   735     1. The source for Django's own ``ImageField`` (in
       
   736        ``django/db/models/fields/files.py``) is a great example of how to
       
   737        subclass ``FileField`` to support a particular type of file, as it
       
   738        incorporates all of the techniques described above.
       
   739 
       
   740     2. Cache file attributes wherever possible. Since files may be stored in
       
   741        remote storage systems, retrieving them may cost extra time, or even
       
   742        money, that isn't always necessary. Once a file is retrieved to obtain
       
   743        some data about its content, cache as much of that data as possible to
       
   744        reduce the number of times the file must be retrieved on subsequent
       
   745        calls for that information.