PageRenderTime 22ms CodeModel.GetById 14ms app.highlight 3ms RepoModel.GetById 0ms app.codeStats 0ms

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