custom-model-fields.txt 29 KB

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