2
0

custom-model-fields.txt 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. =================================
  2. How to create custom model fields
  3. =================================
  4. .. currentmodule:: django.db.models
  5. Introduction
  6. ============
  7. The :doc:`model reference </topics/db/models>` documentation explains how to use
  8. Django's standard field classes -- :class:`~django.db.models.CharField`,
  9. :class:`~django.db.models.DateField`, etc. For many purposes, those classes are
  10. all you'll need. Sometimes, though, the Django version won't meet your precise
  11. requirements, or you'll want to use a field that is entirely different from
  12. those shipped with Django.
  13. Django's built-in field types don't cover every possible database column type --
  14. only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
  15. column types, such as geographic polygons or even user-created types such as
  16. `PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.
  17. .. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html
  18. Alternatively, you may have a complex Python object that can somehow be
  19. serialized to fit into a standard database column type. This is another case
  20. where a ``Field`` subclass will help you use your object with your models.
  21. Our example object
  22. ------------------
  23. Creating custom fields requires a bit of attention to detail. To make things
  24. easier to follow, we'll use a consistent example throughout this document:
  25. wrapping a Python object representing the deal of cards in a hand of Bridge_.
  26. Don't worry, you don't have to know how to play Bridge to follow this example.
  27. You only need to know that 52 cards are dealt out equally to four players, who
  28. are traditionally called *north*, *east*, *south* and *west*. Our class looks
  29. something like this::
  30. class Hand:
  31. """A hand of cards (bridge style)"""
  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: https://en.wikipedia.org/wiki/Contract_bridge
  40. This is 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. Let's start with model fields. If you break it down, a model field provides a
  64. way to take a normal Python object -- string, boolean, ``datetime``, or
  65. something more complex like ``Hand`` -- and convert it to and from a format
  66. that is useful when dealing with the database. (Such a format is also useful
  67. for serialization, but as we'll see later, that is easier once you have the
  68. database side under control).
  69. Fields in a model must somehow be converted to fit into an existing database
  70. column type. Different databases provide different sets of valid column types,
  71. but the rule is still the same: those are the only types you have to work
  72. with. Anything you want to store in the database must fit into one of
  73. those types.
  74. Normally, you're either writing a Django field to match a particular database
  75. column type, or you will need a way to convert your data to, 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 predetermined 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 :doc:`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, uniqueness and so
  86. forth. Storing all that information is handled by ``Field``. We'll get into the
  87. precise details of what ``Field`` can do later on; for now, suffice it to say
  88. that everything descends from ``Field`` and then customizes key pieces of the
  89. 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 :doc:`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. ``__init__()`` method of :class:`~django.db.models.Field` (or your parent
  122. 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. description = "A hand of cards (bridge style)"
  131. def __init__(self, *args, **kwargs):
  132. kwargs["max_length"] = 104
  133. super().__init__(*args, **kwargs)
  134. Our ``HandField`` accepts most of the standard field options (see the list
  135. below), but we ensure it has a fixed length, since it only needs to hold 52
  136. card values plus their suits; 104 characters in total.
  137. .. note::
  138. Many of Django's model fields accept options that they don't do anything
  139. with. For example, you can pass both
  140. :attr:`~django.db.models.Field.editable` and
  141. :attr:`~django.db.models.DateField.auto_now` to a
  142. :class:`django.db.models.DateField` and it will ignore the
  143. :attr:`~django.db.models.Field.editable` parameter
  144. (:attr:`~django.db.models.DateField.auto_now` being set implies
  145. ``editable=False``). No error is raised in this case.
  146. This behavior simplifies the field classes, because they don't need to
  147. check for options that aren't necessary. They pass all the options to
  148. the parent class and then don't use them later on. It's up to you whether
  149. you want your fields to be more strict about the options they select, or to
  150. use the more permissive behavior of the current fields.
  151. The ``Field.__init__()`` method takes the following parameters:
  152. * :attr:`~django.db.models.Field.verbose_name`
  153. * ``name``
  154. * :attr:`~django.db.models.Field.primary_key`
  155. * :attr:`~django.db.models.CharField.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. * ``rel``: Used for related fields (like :class:`ForeignKey`). For advanced
  161. use only.
  162. * :attr:`~django.db.models.Field.default`
  163. * :attr:`~django.db.models.Field.editable`
  164. * ``serialize``: If ``False``, the field will not be serialized when the model
  165. is passed to Django's :doc:`serializers </topics/serialization>`. Defaults to
  166. ``True``.
  167. * :attr:`~django.db.models.Field.unique_for_date`
  168. * :attr:`~django.db.models.Field.unique_for_month`
  169. * :attr:`~django.db.models.Field.unique_for_year`
  170. * :attr:`~django.db.models.Field.choices`
  171. * :attr:`~django.db.models.Field.help_text`
  172. * :attr:`~django.db.models.Field.db_column`
  173. * :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
  174. backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
  175. ignore this option.
  176. * :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was
  177. automatically created, as for the :class:`~django.db.models.OneToOneField`
  178. used by model inheritance. For advanced use only.
  179. All of the options without an explanation in the above list have the same
  180. meaning they do for normal Django fields. See the :doc:`field documentation
  181. </ref/models/fields>` for examples and details.
  182. .. _custom-field-deconstruct-method:
  183. Field deconstruction
  184. --------------------
  185. The counterpoint to writing your ``__init__()`` method is writing the
  186. :meth:`~.Field.deconstruct` method. It's used during :doc:`model migrations
  187. </topics/migrations>` to tell Django how to take an instance of your new field
  188. and reduce it to a serialized form - in particular, what arguments to pass to
  189. ``__init__()`` to recreate it.
  190. If you haven't added any extra options on top of the field you inherited from,
  191. then there's no need to write a new ``deconstruct()`` method. If, however,
  192. you're changing the arguments passed in ``__init__()`` (like we are in
  193. ``HandField``), you'll need to supplement the values being passed.
  194. ``deconstruct()`` returns a tuple of four items: the field's attribute name,
  195. the full import path of the field class, the positional arguments (as a list),
  196. and the keyword arguments (as a dict). Note this is different from the
  197. ``deconstruct()`` method :ref:`for custom classes <custom-deconstruct-method>`
  198. which returns a tuple of three things.
  199. As a custom field author, you don't need to care about the first two values;
  200. the base ``Field`` class has all the code to work out the field's attribute
  201. name and import path. You do, however, have to care about the positional
  202. and keyword arguments, as these are likely the things you are changing.
  203. For example, in our ``HandField`` class we're always forcibly setting
  204. max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``
  205. class will see this and try to return it in the keyword arguments; thus,
  206. we can drop it from the keyword arguments for readability::
  207. from django.db import models
  208. class HandField(models.Field):
  209. def __init__(self, *args, **kwargs):
  210. kwargs["max_length"] = 104
  211. super().__init__(*args, **kwargs)
  212. def deconstruct(self):
  213. name, path, args, kwargs = super().deconstruct()
  214. del kwargs["max_length"]
  215. return name, path, args, kwargs
  216. If you add a new keyword argument, you need to write code in ``deconstruct()``
  217. that puts its value into ``kwargs`` yourself. You should also omit the value
  218. from ``kwargs`` when it isn't necessary to reconstruct the state of the field,
  219. such as when the default value is being used::
  220. from django.db import models
  221. class CommaSepField(models.Field):
  222. "Implements comma-separated storage of lists"
  223. def __init__(self, separator=",", *args, **kwargs):
  224. self.separator = separator
  225. super().__init__(*args, **kwargs)
  226. def deconstruct(self):
  227. name, path, args, kwargs = super().deconstruct()
  228. # Only include kwarg if it's not the default
  229. if self.separator != ",":
  230. kwargs["separator"] = self.separator
  231. return name, path, args, kwargs
  232. More complex examples are beyond the scope of this document, but remember -
  233. for any configuration of your Field instance, ``deconstruct()`` must return
  234. arguments that you can pass to ``__init__`` to reconstruct that state.
  235. Pay extra attention if you set new default values for arguments in the
  236. ``Field`` superclass; you want to make sure they're always included, rather
  237. than disappearing if they take on the old default value.
  238. In addition, try to avoid returning values as positional arguments; where
  239. possible, return values as keyword arguments for maximum future compatibility.
  240. If you change the names of things more often than their position in the
  241. constructor's argument list, you might prefer positional, but bear in mind that
  242. people will be reconstructing your field from the serialized version for quite
  243. a while (possibly years), depending how long your migrations live for.
  244. You can see the results of deconstruction by looking in migrations that include
  245. the field, and you can test deconstruction in unit tests by deconstructing and
  246. reconstructing the field::
  247. name, path, args, kwargs = my_field_instance.deconstruct()
  248. new_instance = MyField(*args, **kwargs)
  249. self.assertEqual(my_field_instance.some_attribute, new_instance.some_attribute)
  250. .. _custom-field-non_db_attrs:
  251. Field attributes not affecting database column definition
  252. ---------------------------------------------------------
  253. You can override ``Field.non_db_attrs`` to customize attributes of a field that
  254. don't affect a column definition. It's used during model migrations to detect
  255. no-op ``AlterField`` operations.
  256. For example::
  257. class CommaSepField(models.Field):
  258. @property
  259. def non_db_attrs(self):
  260. return super().non_db_attrs + ("separator",)
  261. Changing a custom field's base class
  262. ------------------------------------
  263. You can't change the base class of a custom field because Django won't detect
  264. the change and make a migration for it. For example, if you start with::
  265. class CustomCharField(models.CharField): ...
  266. and then decide that you want to use ``TextField`` instead, you can't change
  267. the subclass like this::
  268. class CustomCharField(models.TextField): ...
  269. Instead, you must create a new custom field class and update your models to
  270. reference it::
  271. class CustomCharField(models.CharField): ...
  272. class CustomTextField(models.TextField): ...
  273. As discussed in :ref:`removing fields <migrations-removing-model-fields>`, you
  274. must retain the original ``CustomCharField`` class as long as you have
  275. migrations that reference it.
  276. Documenting your custom field
  277. -----------------------------
  278. As always, you should document your field type, so users will know what it is.
  279. In addition to providing a docstring for it, which is useful for developers,
  280. you can also allow users of the admin app to see a short description of the
  281. field type via the :doc:`django.contrib.admindocs
  282. </ref/contrib/admin/admindocs>` application. To do this provide descriptive
  283. text in a :attr:`~Field.description` class attribute of your custom field. In
  284. the above example, the description displayed by the ``admindocs`` application
  285. for a ``HandField`` will be 'A hand of cards (bridge style)'.
  286. In the :mod:`django.contrib.admindocs` display, the field description is
  287. interpolated with ``field.__dict__`` which allows the description to
  288. incorporate arguments of the field. For example, the description for
  289. :class:`~django.db.models.CharField` is::
  290. description = _("String (up to %(max_length)s)")
  291. Useful methods
  292. --------------
  293. Once you've created your :class:`~django.db.models.Field` subclass, you might
  294. consider overriding a few standard methods, depending on your field's behavior.
  295. The list of methods below is in approximately decreasing order of importance,
  296. so start from the top.
  297. .. _custom-database-types:
  298. Custom database types
  299. ~~~~~~~~~~~~~~~~~~~~~
  300. Say you've created a PostgreSQL custom type called ``mytype``. You can
  301. subclass ``Field`` and implement the :meth:`~Field.db_type` method, like so::
  302. from django.db import models
  303. class MytypeField(models.Field):
  304. def db_type(self, connection):
  305. return "mytype"
  306. Once you have ``MytypeField``, you can use it in any model, just like any other
  307. ``Field`` type::
  308. class Person(models.Model):
  309. name = models.CharField(max_length=80)
  310. something_else = MytypeField()
  311. If you aim to build a database-agnostic application, you should account for
  312. differences in database column types. For example, the date/time column type
  313. in PostgreSQL is called ``timestamp``, while the same column in MySQL is called
  314. ``datetime``. You can handle this in a :meth:`~Field.db_type` method by
  315. checking the ``connection.vendor`` attribute. Current built-in vendor names
  316. are: ``sqlite``, ``postgresql``, ``mysql``, and ``oracle``.
  317. For example::
  318. class MyDateField(models.Field):
  319. def db_type(self, connection):
  320. if connection.vendor == "mysql":
  321. return "datetime"
  322. else:
  323. return "timestamp"
  324. The :meth:`~Field.db_type` and :meth:`~Field.rel_db_type` methods are called by
  325. Django when the framework constructs the ``CREATE TABLE`` statements for your
  326. application -- that is, when you first create your tables. The methods are also
  327. called when constructing a ``WHERE`` clause that includes the model field --
  328. that is, when you retrieve data using QuerySet methods like ``get()``,
  329. ``filter()``, and ``exclude()`` and have the model field as an argument.
  330. Some database column types accept parameters, such as ``CHAR(25)``, where the
  331. parameter ``25`` represents the maximum column length. In cases like these,
  332. it's more flexible if the parameter is specified in the model rather than being
  333. hard-coded in the ``db_type()`` method. For example, it wouldn't make much
  334. sense to have a ``CharMaxlength25Field``, shown here::
  335. # This is a silly example of hard-coded parameters.
  336. class CharMaxlength25Field(models.Field):
  337. def db_type(self, connection):
  338. return "char(25)"
  339. # In the model:
  340. class MyModel(models.Model):
  341. # ...
  342. my_field = CharMaxlength25Field()
  343. The better way of doing this would be to make the parameter specifiable at run
  344. time -- i.e., when the class is instantiated. To do that, implement
  345. ``Field.__init__()``, like so::
  346. # This is a much more flexible example.
  347. class BetterCharField(models.Field):
  348. def __init__(self, max_length, *args, **kwargs):
  349. self.max_length = max_length
  350. super().__init__(*args, **kwargs)
  351. def db_type(self, connection):
  352. return "char(%s)" % self.max_length
  353. # In the model:
  354. class MyModel(models.Model):
  355. # ...
  356. my_field = BetterCharField(25)
  357. Finally, if your column requires truly complex SQL setup, return ``None`` from
  358. :meth:`.db_type`. This will cause Django's SQL creation code to skip
  359. over this field. You are then responsible for creating the column in the right
  360. table in some other way, but this gives you a way to tell Django to get out of
  361. the way.
  362. The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``
  363. and ``OneToOneField`` that point to another field to determine their database
  364. column data types. For example, if you have an ``UnsignedAutoField``, you also
  365. need the foreign keys that point to that field to use the same data type::
  366. # MySQL unsigned integer (range 0 to 4294967295).
  367. class UnsignedAutoField(models.AutoField):
  368. def db_type(self, connection):
  369. return "integer UNSIGNED AUTO_INCREMENT"
  370. def rel_db_type(self, connection):
  371. return "integer UNSIGNED"
  372. .. _converting-values-to-python-objects:
  373. Converting values to Python objects
  374. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  375. If your custom :class:`~Field` class deals with data structures that are more
  376. complex than strings, dates, integers, or floats, then you may need to override
  377. :meth:`~Field.from_db_value` and :meth:`~Field.to_python`.
  378. If present for the field subclass, ``from_db_value()`` will be called in all
  379. circumstances when the data is loaded from the database, including in
  380. aggregates and :meth:`~django.db.models.query.QuerySet.values` calls.
  381. ``to_python()`` is called by deserialization and during the
  382. :meth:`~django.db.models.Model.clean` method used from forms.
  383. As a general rule, ``to_python()`` should deal gracefully with any of the
  384. following arguments:
  385. * An instance of the correct type (e.g., ``Hand`` in our ongoing example).
  386. * A string
  387. * ``None`` (if the field allows ``null=True``)
  388. In our ``HandField`` class, we're storing the data as a ``VARCHAR`` field in
  389. the database, so we need to be able to process strings and ``None`` in the
  390. ``from_db_value()``. In ``to_python()``, we need to also handle ``Hand``
  391. instances::
  392. import re
  393. from django.core.exceptions import ValidationError
  394. from django.db import models
  395. from django.utils.translation import gettext_lazy as _
  396. def parse_hand(hand_string):
  397. """Takes a string of cards and splits into a full hand."""
  398. p1 = re.compile(".{26}")
  399. p2 = re.compile("..")
  400. args = [p2.findall(x) for x in p1.findall(hand_string)]
  401. if len(args) != 4:
  402. raise ValidationError(_("Invalid input for a Hand instance"))
  403. return Hand(*args)
  404. class HandField(models.Field):
  405. # ...
  406. def from_db_value(self, value, expression, connection):
  407. if value is None:
  408. return value
  409. return parse_hand(value)
  410. def to_python(self, value):
  411. if isinstance(value, Hand):
  412. return value
  413. if value is None:
  414. return value
  415. return parse_hand(value)
  416. Notice that we always return a ``Hand`` instance from these methods. That's the
  417. Python object type we want to store in the model's attribute.
  418. For ``to_python()``, if anything goes wrong during value conversion, you should
  419. raise a :exc:`~django.core.exceptions.ValidationError` exception.
  420. .. _converting-python-objects-to-query-values:
  421. Converting Python objects to query values
  422. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  423. Since using a database requires conversion in both ways, if you override
  424. :meth:`~Field.from_db_value` you also have to override
  425. :meth:`~Field.get_prep_value` to convert Python objects back to query values.
  426. For example::
  427. class HandField(models.Field):
  428. # ...
  429. def get_prep_value(self, value):
  430. return "".join(
  431. ["".join(l) for l in (value.north, value.east, value.south, value.west)]
  432. )
  433. .. warning::
  434. If your custom field uses the ``CHAR``, ``VARCHAR`` or ``TEXT``
  435. types for MySQL, you must make sure that :meth:`.get_prep_value`
  436. always returns a string type. MySQL performs flexible and unexpected
  437. matching when a query is performed on these types and the provided
  438. value is an integer, which can cause queries to include unexpected
  439. objects in their results. This problem cannot occur if you always
  440. return a string type from :meth:`.get_prep_value`.
  441. .. _converting-query-values-to-database-values:
  442. Converting query values to database values
  443. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  444. Some data types (for example, dates) need to be in a specific format
  445. before they can be used by a database backend.
  446. :meth:`~Field.get_db_prep_value` is the method where those conversions should
  447. be made. The specific connection that will be used for the query is
  448. passed as the ``connection`` parameter. This allows you to use
  449. backend-specific conversion logic if it is required.
  450. For example, Django uses the following method for its
  451. :class:`BinaryField`::
  452. def get_db_prep_value(self, value, connection, prepared=False):
  453. value = super().get_db_prep_value(value, connection, prepared)
  454. if value is not None:
  455. return connection.Database.Binary(value)
  456. return value
  457. In case your custom field needs a special conversion when being saved that is
  458. not the same as the conversion used for normal query parameters, you can
  459. override :meth:`~Field.get_db_prep_save`.
  460. .. _preprocessing-values-before-saving:
  461. Preprocessing values before saving
  462. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  463. If you want to preprocess the value just before saving, you can use
  464. :meth:`~Field.pre_save`. For example, Django's
  465. :class:`~django.db.models.DateTimeField` uses this method to set the attribute
  466. correctly in the case of :attr:`~django.db.models.DateField.auto_now` or
  467. :attr:`~django.db.models.DateField.auto_now_add`.
  468. If you do override this method, you must return the value of the attribute at
  469. the end. You should also update the model's attribute if you make any changes
  470. to the value so that code holding references to the model will always see the
  471. correct value.
  472. .. _specifying-form-field-for-model-field:
  473. Specifying the form field for a model field
  474. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  475. To customize the form field used by :class:`~django.forms.ModelForm`, you can
  476. override :meth:`~Field.formfield`.
  477. The form field class can be specified via the ``form_class`` and
  478. ``choices_form_class`` arguments; the latter is used if the field has choices
  479. specified, the former otherwise. If these arguments are not provided,
  480. :class:`~django.forms.CharField` or :class:`~django.forms.TypedChoiceField`
  481. will be used.
  482. All of the ``kwargs`` dictionary is passed directly to the form field's
  483. ``__init__()`` method. Normally, all you need to do is set up a good default
  484. for the ``form_class`` (and maybe ``choices_form_class``) argument and then
  485. delegate further handling to the parent class. This might require you to write
  486. a custom form field (and even a form widget). See the :doc:`forms documentation
  487. </topics/forms/index>` for information about this.
  488. If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you
  489. can override the :meth:`~Field.formfield` method to return ``None``.
  490. Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
  491. as::
  492. class HandField(models.Field):
  493. # ...
  494. def formfield(self, **kwargs):
  495. # Exclude the field from the ModelForm when some condition is met.
  496. some_condition = kwargs.get("some_condition", False)
  497. if some_condition:
  498. return None
  499. # Set up some defaults while letting the caller override them.
  500. defaults = {"form_class": MyFormField}
  501. defaults.update(kwargs)
  502. return super().formfield(**defaults)
  503. This assumes we've imported a ``MyFormField`` field class (which has its own
  504. default widget). This document doesn't cover the details of writing custom form
  505. fields.
  506. .. _helper functions: ../forms/#generating-forms-for-models
  507. .. _forms documentation: ../forms/
  508. .. _emulating-built-in-field-types:
  509. Emulating built-in field types
  510. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  511. If you have created a :meth:`.db_type` method, you don't need to worry about
  512. :meth:`.get_internal_type` -- it won't be used much. Sometimes, though, your
  513. database storage is similar in type to some other field, so you can use that
  514. other field's logic to create the right column.
  515. For example::
  516. class HandField(models.Field):
  517. # ...
  518. def get_internal_type(self):
  519. return "CharField"
  520. No matter which database backend we are using, this will mean that
  521. :djadmin:`migrate` and other SQL commands create the right column type for
  522. storing a string.
  523. If :meth:`.get_internal_type` returns a string that is not known to Django for
  524. the database backend you are using -- that is, it doesn't appear in
  525. ``django.db.backends.<db_name>.base.DatabaseWrapper.data_types`` -- the string
  526. will still be used by the serializer, but the default :meth:`~Field.db_type`
  527. method will return ``None``. See the documentation of :meth:`~Field.db_type`
  528. for reasons why this might be useful. Putting a descriptive string in as the
  529. type of the field for the serializer is a useful idea if you're ever going to
  530. be using the serializer output in some other place, outside of Django.
  531. .. _converting-model-field-to-serialization:
  532. Converting field data for serialization
  533. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  534. To customize how the values are serialized by a serializer, you can override
  535. :meth:`~Field.value_to_string`. Using :meth:`~Field.value_from_object` is the
  536. best way to get the field's value prior to serialization. For example, since
  537. ``HandField`` uses strings for its data storage anyway, we can reuse some
  538. existing conversion code::
  539. class HandField(models.Field):
  540. # ...
  541. def value_to_string(self, obj):
  542. value = self.value_from_object(obj)
  543. return self.get_prep_value(value)
  544. Some general advice
  545. -------------------
  546. Writing a custom field can be a tricky process, particularly if you're doing
  547. complex conversions between your Python types and your database and
  548. serialization formats. Here are a couple of tips to make things go more
  549. smoothly:
  550. #. Look at the existing Django fields (in
  551. :source:`django/db/models/fields/__init__.py`) for inspiration. Try to find
  552. a field that's similar to what you want and extend it a little bit,
  553. instead of creating an entirely new field from scratch.
  554. #. Put a ``__str__()`` method on the class you're wrapping up as a field. There
  555. are a lot of places where the default behavior of the field code is to call
  556. ``str()`` on the value. (In our examples in this document, ``value`` would
  557. be a ``Hand`` instance, not a ``HandField``). So if your ``__str__()``
  558. method automatically converts to the string form of your Python object, you
  559. can save yourself a lot of work.
  560. Writing a ``FileField`` subclass
  561. ================================
  562. In addition to the above methods, fields that deal with files have a few other
  563. special requirements which must be taken into account. The majority of the
  564. mechanics provided by ``FileField``, such as controlling database storage and
  565. retrieval, can remain unchanged, leaving subclasses to deal with the challenge
  566. of supporting a particular type of file.
  567. Django provides a ``File`` class, which is used as a proxy to the file's
  568. contents and operations. This can be subclassed to customize how the file is
  569. accessed, and what methods are available. It lives at
  570. ``django.db.models.fields.files``, and its default behavior is explained in the
  571. :doc:`file documentation </ref/files/file>`.
  572. Once a subclass of ``File`` is created, the new ``FileField`` subclass must be
  573. told to use it. To do so, assign the new ``File`` subclass to the special
  574. ``attr_class`` attribute of the ``FileField`` subclass.
  575. A few suggestions
  576. -----------------
  577. In addition to the above details, there are a few guidelines which can greatly
  578. improve the efficiency and readability of the field's code.
  579. #. The source for Django's own ``ImageField`` (in
  580. :source:`django/db/models/fields/files.py`) is a great example of how to
  581. subclass ``FileField`` to support a particular type of file, as it
  582. incorporates all of the techniques described above.
  583. #. Cache file attributes wherever possible. Since files may be stored in
  584. remote storage systems, retrieving them may cost extra time, or even
  585. money, that isn't always necessary. Once a file is retrieved to obtain
  586. some data about its content, cache as much of that data as possible to
  587. reduce the number of times the file must be retrieved on subsequent
  588. calls for that information.