fields.txt 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. =====================
  2. Model field reference
  3. =====================
  4. .. module:: django.db.models.fields
  5. :synopsis: Built-in field types.
  6. .. currentmodule:: django.db.models
  7. This document contains all the API references of :class:`Field` including the
  8. `field options`_ and `field types`_ Django offers.
  9. .. seealso::
  10. If the built-in fields don't do the trick, you can try `django-localflavor
  11. <https://github.com/django/django-localflavor>`_ (`documentation
  12. <https://django-localflavor.readthedocs.io/>`_), which contains assorted
  13. pieces of code that are useful for particular countries and cultures.
  14. Also, you can easily :doc:`write your own custom model fields
  15. </howto/custom-model-fields>`.
  16. .. note::
  17. Technically, these models are defined in :mod:`django.db.models.fields`, but
  18. for convenience they're imported into :mod:`django.db.models`; the standard
  19. convention is to use ``from django.db import models`` and refer to fields as
  20. ``models.<Foo>Field``.
  21. .. _common-model-field-options:
  22. Field options
  23. =============
  24. The following arguments are available to all field types. All are optional.
  25. ``null``
  26. --------
  27. .. attribute:: Field.null
  28. If ``True``, Django will store empty values as ``NULL`` in the database. Default
  29. is ``False``.
  30. Avoid using :attr:`~Field.null` on string-based fields such as
  31. :class:`CharField` and :class:`TextField`. If a string-based field has
  32. ``null=True``, that means it has two possible values for "no data": ``NULL``,
  33. and the empty string. In most cases, it's redundant to have two possible values
  34. for "no data;" the Django convention is to use the empty string, not
  35. ``NULL``. One exception is when a :class:`CharField` has both ``unique=True``
  36. and ``blank=True`` set. In this situation, ``null=True`` is required to avoid
  37. unique constraint violations when saving multiple objects with blank values.
  38. For both string-based and non-string-based fields, you will also need to
  39. set ``blank=True`` if you wish to permit empty values in forms, as the
  40. :attr:`~Field.null` parameter only affects database storage
  41. (see :attr:`~Field.blank`).
  42. .. note::
  43. When using the Oracle database backend, the value ``NULL`` will be stored to
  44. denote the empty string regardless of this attribute.
  45. If you want to accept :attr:`~Field.null` values with :class:`BooleanField`,
  46. use :class:`NullBooleanField` instead.
  47. ``blank``
  48. ---------
  49. .. attribute:: Field.blank
  50. If ``True``, the field is allowed to be blank. Default is ``False``.
  51. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  52. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  53. a field has ``blank=True``, form validation will allow entry of an empty value.
  54. If a field has ``blank=False``, the field will be required.
  55. .. _field-choices:
  56. ``choices``
  57. -----------
  58. .. attribute:: Field.choices
  59. An iterable (e.g., a list or tuple) consisting itself of iterables of exactly
  60. two items (e.g. ``[(A, B), (A, B) ...]``) to use as choices for this field. If
  61. this is given, the default form widget will be a select box with these choices
  62. instead of the standard text field.
  63. The first element in each tuple is the actual value to be set on the model,
  64. and the second element is the human-readable name. For example::
  65. YEAR_IN_SCHOOL_CHOICES = (
  66. ('FR', 'Freshman'),
  67. ('SO', 'Sophomore'),
  68. ('JR', 'Junior'),
  69. ('SR', 'Senior'),
  70. )
  71. Generally, it's best to define choices inside a model class, and to
  72. define a suitably-named constant for each value::
  73. from django.db import models
  74. class Student(models.Model):
  75. FRESHMAN = 'FR'
  76. SOPHOMORE = 'SO'
  77. JUNIOR = 'JR'
  78. SENIOR = 'SR'
  79. YEAR_IN_SCHOOL_CHOICES = (
  80. (FRESHMAN, 'Freshman'),
  81. (SOPHOMORE, 'Sophomore'),
  82. (JUNIOR, 'Junior'),
  83. (SENIOR, 'Senior'),
  84. )
  85. year_in_school = models.CharField(
  86. max_length=2,
  87. choices=YEAR_IN_SCHOOL_CHOICES,
  88. default=FRESHMAN,
  89. )
  90. def is_upperclass(self):
  91. return self.year_in_school in (self.JUNIOR, self.SENIOR)
  92. Though you can define a choices list outside of a model class and then
  93. refer to it, defining the choices and names for each choice inside the
  94. model class keeps all of that information with the class that uses it,
  95. and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
  96. will work anywhere that the ``Student`` model has been imported).
  97. You can also collect your available choices into named groups that can
  98. be used for organizational purposes::
  99. MEDIA_CHOICES = (
  100. ('Audio', (
  101. ('vinyl', 'Vinyl'),
  102. ('cd', 'CD'),
  103. )
  104. ),
  105. ('Video', (
  106. ('vhs', 'VHS Tape'),
  107. ('dvd', 'DVD'),
  108. )
  109. ),
  110. ('unknown', 'Unknown'),
  111. )
  112. The first element in each tuple is the name to apply to the group. The
  113. second element is an iterable of 2-tuples, with each 2-tuple containing
  114. a value and a human-readable name for an option. Grouped options may be
  115. combined with ungrouped options within a single list (such as the
  116. `unknown` option in this example).
  117. For each model field that has :attr:`~Field.choices` set, Django will add a
  118. method to retrieve the human-readable name for the field's current value. See
  119. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  120. documentation.
  121. Note that choices can be any iterable object -- not necessarily a list or tuple.
  122. This lets you construct choices dynamically. But if you find yourself hacking
  123. :attr:`~Field.choices` to be dynamic, you're probably better off using a proper
  124. database table with a :class:`ForeignKey`. :attr:`~Field.choices` is meant for
  125. static data that doesn't change much, if ever.
  126. Unless :attr:`blank=False<Field.blank>` is set on the field along with a
  127. :attr:`~Field.default` then a label containing ``"---------"`` will be rendered
  128. with the select box. To override this behavior, add a tuple to ``choices``
  129. containing ``None``; e.g. ``(None, 'Your String For Display')``.
  130. Alternatively, you can use an empty string instead of ``None`` where this makes
  131. sense - such as on a :class:`~django.db.models.CharField`.
  132. ``db_column``
  133. -------------
  134. .. attribute:: Field.db_column
  135. The name of the database column to use for this field. If this isn't given,
  136. Django will use the field's name.
  137. If your database column name is an SQL reserved word, or contains
  138. characters that aren't allowed in Python variable names -- notably, the
  139. hyphen -- that's OK. Django quotes column and table names behind the
  140. scenes.
  141. ``db_index``
  142. ------------
  143. .. attribute:: Field.db_index
  144. If ``True``, a database index will be created for this field.
  145. ``db_tablespace``
  146. -----------------
  147. .. attribute:: Field.db_tablespace
  148. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  149. this field's index, if this field is indexed. The default is the project's
  150. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
  151. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
  152. support tablespaces for indexes, this option is ignored.
  153. ``default``
  154. -----------
  155. .. attribute:: Field.default
  156. The default value for the field. This can be a value or a callable object. If
  157. callable it will be called every time a new object is created.
  158. The default can't be a mutable object (model instance, ``list``, ``set``, etc.),
  159. as a reference to the same instance of that object would be used as the default
  160. value in all new model instances. Instead, wrap the desired default in a
  161. callable. For example, if you want to specify a default ``dict`` for
  162. :class:`~django.contrib.postgres.fields.JSONField`, use a function::
  163. def contact_default():
  164. return {"email": "to1@example.com"}
  165. contact_info = JSONField("ContactInfo", default=contact_default)
  166. ``lambda``\s can't be used for field options like ``default`` because they
  167. can't be :ref:`serialized by migrations <migration-serializing>`. See that
  168. documentation for other caveats.
  169. For fields like :class:`ForeignKey` that map to model instances, defaults
  170. should be the value of the field they reference (``pk`` unless
  171. :attr:`~ForeignKey.to_field` is set) instead of model instances.
  172. The default value is used when new model instances are created and a value
  173. isn't provided for the field. When the field is a primary key, the default is
  174. also used when the field is set to ``None``.
  175. ``editable``
  176. ------------
  177. .. attribute:: Field.editable
  178. If ``False``, the field will not be displayed in the admin or any other
  179. :class:`~django.forms.ModelForm`. They are also skipped during :ref:`model
  180. validation <validating-objects>`. Default is ``True``.
  181. ``error_messages``
  182. ------------------
  183. .. attribute:: Field.error_messages
  184. The ``error_messages`` argument lets you override the default messages that the
  185. field will raise. Pass in a dictionary with keys matching the error messages you
  186. want to override.
  187. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  188. ``unique``, and ``unique_for_date``. Additional error message keys are
  189. specified for each field in the `Field types`_ section below.
  190. ``help_text``
  191. -------------
  192. .. attribute:: Field.help_text
  193. Extra "help" text to be displayed with the form widget. It's useful for
  194. documentation even if your field isn't used on a form.
  195. Note that this value is *not* HTML-escaped in automatically-generated
  196. forms. This lets you include HTML in :attr:`~Field.help_text` if you so
  197. desire. For example::
  198. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  199. Alternatively you can use plain text and
  200. ``django.utils.html.escape()`` to escape any HTML special characters. Ensure
  201. that you escape any help text that may come from untrusted users to avoid a
  202. cross-site scripting attack.
  203. ``primary_key``
  204. ---------------
  205. .. attribute:: Field.primary_key
  206. If ``True``, this field is the primary key for the model.
  207. If you don't specify ``primary_key=True`` for any field in your model, Django
  208. will automatically add an :class:`AutoField` to hold the primary key, so you
  209. don't need to set ``primary_key=True`` on any of your fields unless you want to
  210. override the default primary-key behavior. For more, see
  211. :ref:`automatic-primary-key-fields`.
  212. ``primary_key=True`` implies :attr:`null=False <Field.null>` and
  213. :attr:`unique=True <Field.unique>`. Only one primary key is allowed on an
  214. object.
  215. The primary key field is read-only. If you change the value of the primary
  216. key on an existing object and then save it, a new object will be created
  217. alongside the old one.
  218. ``unique``
  219. ----------
  220. .. attribute:: Field.unique
  221. If ``True``, this field must be unique throughout the table.
  222. This is enforced at the database level and by model validation. If
  223. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  224. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  225. :meth:`~django.db.models.Model.save` method.
  226. This option is valid on all field types except :class:`ManyToManyField` and
  227. :class:`OneToOneField`.
  228. Note that when ``unique`` is ``True``, you don't need to specify
  229. :attr:`~Field.db_index`, because ``unique`` implies the creation of an index.
  230. .. versionchanged:: 1.11
  231. In older versions, ``unique=True`` can't be used on :class:`FileField`.
  232. ``unique_for_date``
  233. -------------------
  234. .. attribute:: Field.unique_for_date
  235. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  236. require that this field be unique for the value of the date field.
  237. For example, if you have a field ``title`` that has
  238. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  239. records with the same ``title`` and ``pub_date``.
  240. Note that if you set this to point to a :class:`DateTimeField`, only the date
  241. portion of the field will be considered. Besides, when :setting:`USE_TZ` is
  242. ``True``, the check will be performed in the :ref:`current time zone
  243. <default-current-time-zone>` at the time the object gets saved.
  244. This is enforced by :meth:`Model.validate_unique()` during model validation
  245. but not at the database level. If any :attr:`~Field.unique_for_date` constraint
  246. involves fields that are not part of a :class:`~django.forms.ModelForm` (for
  247. example, if one of the fields is listed in ``exclude`` or has
  248. :attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
  249. skip validation for that particular constraint.
  250. ``unique_for_month``
  251. --------------------
  252. .. attribute:: Field.unique_for_month
  253. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  254. respect to the month.
  255. ``unique_for_year``
  256. -------------------
  257. .. attribute:: Field.unique_for_year
  258. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  259. ``verbose_name``
  260. -------------------
  261. .. attribute:: Field.verbose_name
  262. A human-readable name for the field. If the verbose name isn't given, Django
  263. will automatically create it using the field's attribute name, converting
  264. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
  265. ``validators``
  266. -------------------
  267. .. attribute:: Field.validators
  268. A list of validators to run for this field. See the :doc:`validators
  269. documentation </ref/validators>` for more information.
  270. Registering and fetching lookups
  271. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  272. ``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.
  273. The API can be used to customize which lookups are available for a field class, and
  274. how lookups are fetched from a field.
  275. .. _model-field-types:
  276. Field types
  277. ===========
  278. .. currentmodule:: django.db.models
  279. ``AutoField``
  280. -------------
  281. .. class:: AutoField(**options)
  282. An :class:`IntegerField` that automatically increments
  283. according to available IDs. You usually won't need to use this directly; a
  284. primary key field will automatically be added to your model if you don't specify
  285. otherwise. See :ref:`automatic-primary-key-fields`.
  286. ``BigAutoField``
  287. ----------------
  288. .. class:: BigAutoField(**options)
  289. A 64-bit integer, much like an :class:`AutoField` except that it is
  290. guaranteed to fit numbers from ``1`` to ``9223372036854775807``.
  291. ``BigIntegerField``
  292. -------------------
  293. .. class:: BigIntegerField(**options)
  294. A 64-bit integer, much like an :class:`IntegerField` except that it is
  295. guaranteed to fit numbers from ``-9223372036854775808`` to
  296. ``9223372036854775807``. The default form widget for this field is a
  297. :class:`~django.forms.TextInput`.
  298. ``BinaryField``
  299. -------------------
  300. .. class:: BinaryField(**options)
  301. A field to store raw binary data. It only supports ``bytes`` assignment. Be
  302. aware that this field has limited functionality. For example, it is not possible
  303. to filter a queryset on a ``BinaryField`` value. It is also not possible to
  304. include a ``BinaryField`` in a :class:`~django.forms.ModelForm`.
  305. .. admonition:: Abusing ``BinaryField``
  306. Although you might think about storing files in the database, consider that
  307. it is bad design in 99% of the cases. This field is *not* a replacement for
  308. proper :doc:`static files </howto/static-files/index>` handling.
  309. ``BooleanField``
  310. ----------------
  311. .. class:: BooleanField(**options)
  312. A true/false field.
  313. The default form widget for this field is a
  314. :class:`~django.forms.CheckboxInput`.
  315. If you need to accept :attr:`~Field.null` values then use
  316. :class:`NullBooleanField` instead.
  317. The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
  318. isn't defined.
  319. ``CharField``
  320. -------------
  321. .. class:: CharField(max_length=None, **options)
  322. A string field, for small- to large-sized strings.
  323. For large amounts of text, use :class:`~django.db.models.TextField`.
  324. The default form widget for this field is a :class:`~django.forms.TextInput`.
  325. :class:`CharField` has one extra required argument:
  326. .. attribute:: CharField.max_length
  327. The maximum length (in characters) of the field. The max_length is enforced
  328. at the database level and in Django's validation.
  329. .. note::
  330. If you are writing an application that must be portable to multiple
  331. database backends, you should be aware that there are restrictions on
  332. ``max_length`` for some backends. Refer to the :doc:`database backend
  333. notes </ref/databases>` for details.
  334. .. admonition:: MySQL users
  335. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  336. collation (which is *not* the default), there are some issues to be aware
  337. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  338. details.
  339. ``DateField``
  340. -------------
  341. .. class:: DateField(auto_now=False, auto_now_add=False, **options)
  342. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  343. optional arguments:
  344. .. attribute:: DateField.auto_now
  345. Automatically set the field to now every time the object is saved. Useful
  346. for "last-modified" timestamps. Note that the current date is *always*
  347. used; it's not just a default value that you can override.
  348. The field is only automatically updated when calling :meth:`Model.save()
  349. <django.db.models.Model.save>`. The field isn't updated when making updates
  350. to other fields in other ways such as :meth:`QuerySet.update()
  351. <django.db.models.query.QuerySet.update>`, though you can specify a custom
  352. value for the field in an update like that.
  353. .. attribute:: DateField.auto_now_add
  354. Automatically set the field to now when the object is first created. Useful
  355. for creation of timestamps. Note that the current date is *always* used;
  356. it's not just a default value that you can override. So even if you
  357. set a value for this field when creating the object, it will be ignored.
  358. If you want to be able to modify this field, set the following instead of
  359. ``auto_now_add=True``:
  360. * For :class:`DateField`: ``default=date.today`` - from
  361. :meth:`datetime.date.today`
  362. * For :class:`DateTimeField`: ``default=timezone.now`` - from
  363. :func:`django.utils.timezone.now`
  364. The default form widget for this field is a
  365. :class:`~django.forms.TextInput`. The admin adds a JavaScript calendar,
  366. and a shortcut for "Today". Includes an additional ``invalid_date`` error
  367. message key.
  368. The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.
  369. Any combination of these options will result in an error.
  370. .. note::
  371. As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
  372. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  373. set.
  374. .. note::
  375. The ``auto_now`` and ``auto_now_add`` options will always use the date in
  376. the :ref:`default timezone <default-current-time-zone>` at the moment of
  377. creation or update. If you need something different, you may want to
  378. consider simply using your own callable default or overriding ``save()``
  379. instead of using ``auto_now`` or ``auto_now_add``; or using a
  380. ``DateTimeField`` instead of a ``DateField`` and deciding how to handle the
  381. conversion from datetime to date at display time.
  382. ``DateTimeField``
  383. -----------------
  384. .. class:: DateTimeField(auto_now=False, auto_now_add=False, **options)
  385. A date and time, represented in Python by a ``datetime.datetime`` instance.
  386. Takes the same extra arguments as :class:`DateField`.
  387. The default form widget for this field is a single
  388. :class:`~django.forms.TextInput`. The admin uses two separate
  389. :class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
  390. ``DecimalField``
  391. ----------------
  392. .. class:: DecimalField(max_digits=None, decimal_places=None, **options)
  393. A fixed-precision decimal number, represented in Python by a
  394. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  395. .. attribute:: DecimalField.max_digits
  396. The maximum number of digits allowed in the number. Note that this number
  397. must be greater than or equal to ``decimal_places``.
  398. .. attribute:: DecimalField.decimal_places
  399. The number of decimal places to store with the number.
  400. For example, to store numbers up to ``999`` with a resolution of 2 decimal
  401. places, you'd use::
  402. models.DecimalField(..., max_digits=5, decimal_places=2)
  403. And to store numbers up to approximately one billion with a resolution of 10
  404. decimal places::
  405. models.DecimalField(..., max_digits=19, decimal_places=10)
  406. The default form widget for this field is a :class:`~django.forms.NumberInput`
  407. when :attr:`~django.forms.Field.localize` is ``False`` or
  408. :class:`~django.forms.TextInput` otherwise.
  409. .. note::
  410. For more information about the differences between the
  411. :class:`FloatField` and :class:`DecimalField` classes, please
  412. see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`.
  413. ``DurationField``
  414. -----------------
  415. .. class:: DurationField(**options)
  416. A field for storing periods of time - modeled in Python by
  417. :class:`~python:datetime.timedelta`. When used on PostgreSQL, the data type
  418. used is an ``interval`` and on Oracle the data type is ``INTERVAL DAY(9) TO
  419. SECOND(6)``. Otherwise a ``bigint`` of microseconds is used.
  420. .. note::
  421. Arithmetic with ``DurationField`` works in most cases. However on all
  422. databases other than PostgreSQL, comparing the value of a ``DurationField``
  423. to arithmetic on ``DateTimeField`` instances will not work as expected.
  424. ``EmailField``
  425. --------------
  426. .. class:: EmailField(max_length=254, **options)
  427. A :class:`CharField` that checks that the value is a valid email address. It
  428. uses :class:`~django.core.validators.EmailValidator` to validate the input.
  429. ``FileField``
  430. -------------
  431. .. class:: FileField(upload_to=None, max_length=100, **options)
  432. A file-upload field.
  433. .. note::
  434. The ``primary_key`` argument isn't supported and will raise a an error if
  435. used.
  436. Has two optional arguments:
  437. .. attribute:: FileField.upload_to
  438. This attribute provides a way of setting the upload directory and file name,
  439. and can be set in two ways. In both cases, the value is passed to the
  440. :meth:`Storage.save() <django.core.files.storage.Storage.save>` method.
  441. If you specify a string value, it may contain :func:`~time.strftime`
  442. formatting, which will be replaced by the date/time of the file upload (so
  443. that uploaded files don't fill up the given directory). For example::
  444. class MyModel(models.Model):
  445. # file will be uploaded to MEDIA_ROOT/uploads
  446. upload = models.FileField(upload_to='uploads/')
  447. # or...
  448. # file will be saved to MEDIA_ROOT/uploads/2015/01/30
  449. upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
  450. If you are using the default
  451. :class:`~django.core.files.storage.FileSystemStorage`, the string value
  452. will be appended to your :setting:`MEDIA_ROOT` path to form the location on
  453. the local filesystem where uploaded files will be stored. If you are using
  454. a different storage, check that storage's documentation to see how it
  455. handles ``upload_to``.
  456. ``upload_to`` may also be a callable, such as a function. This will be
  457. called to obtain the upload path, including the filename. This callable must
  458. accept two arguments and return a Unix-style path (with forward slashes)
  459. to be passed along to the storage system. The two arguments are:
  460. ====================== ===============================================
  461. Argument Description
  462. ====================== ===============================================
  463. ``instance`` An instance of the model where the
  464. ``FileField`` is defined. More specifically,
  465. this is the particular instance where the
  466. current file is being attached.
  467. In most cases, this object will not have been
  468. saved to the database yet, so if it uses the
  469. default ``AutoField``, *it might not yet have a
  470. value for its primary key field*.
  471. ``filename`` The filename that was originally given to the
  472. file. This may or may not be taken into account
  473. when determining the final destination path.
  474. ====================== ===============================================
  475. For example::
  476. def user_directory_path(instance, filename):
  477. # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
  478. return 'user_{0}/{1}'.format(instance.user.id, filename)
  479. class MyModel(models.Model):
  480. upload = models.FileField(upload_to=user_directory_path)
  481. .. attribute:: FileField.storage
  482. A storage object, which handles the storage and retrieval of your
  483. files. See :doc:`/topics/files` for details on how to provide this object.
  484. The default form widget for this field is a
  485. :class:`~django.forms.ClearableFileInput`.
  486. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  487. takes a few steps:
  488. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  489. full path to a directory where you'd like Django to store uploaded files.
  490. (For performance, these files are not stored in the database.) Define
  491. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  492. that this directory is writable by the Web server's user account.
  493. 2. Add the :class:`FileField` or :class:`ImageField` to your model, defining
  494. the :attr:`~FileField.upload_to` option to specify a subdirectory of
  495. :setting:`MEDIA_ROOT` to use for uploaded files.
  496. 3. All that will be stored in your database is a path to the file
  497. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  498. convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
  499. provided by Django. For example, if your :class:`ImageField` is called
  500. ``mug_shot``, you can get the absolute path to your image in a template with
  501. ``{{ object.mug_shot.url }}``.
  502. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  503. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  504. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
  505. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
  506. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
  507. the directory ``/home/media/photos/2007/01/15``.
  508. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
  509. size, you could use the :attr:`~django.core.files.File.name` and
  510. :attr:`~django.core.files.File.size` attributes respectively; for more
  511. information on the available attributes and methods, see the
  512. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
  513. topic guide.
  514. .. note::
  515. The file is saved as part of saving the model in the database, so the actual
  516. file name used on disk cannot be relied on until after the model has been
  517. saved.
  518. The uploaded file's relative URL can be obtained using the
  519. :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
  520. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
  521. underlying :class:`~django.core.files.storage.Storage` class.
  522. .. _file-upload-security:
  523. Note that whenever you deal with uploaded files, you should pay close attention
  524. to where you're uploading them and what type of files they are, to avoid
  525. security holes. *Validate all uploaded files* so that you're sure the files are
  526. what you think they are. For example, if you blindly let somebody upload files,
  527. without validation, to a directory that's within your Web server's document
  528. root, then somebody could upload a CGI or PHP script and execute that script by
  529. visiting its URL on your site. Don't allow that.
  530. Also note that even an uploaded HTML file, since it can be executed by the
  531. browser (though not by the server), can pose security threats that are
  532. equivalent to XSS or CSRF attacks.
  533. :class:`FileField` instances are created in your database as ``varchar``
  534. columns with a default max length of 100 characters. As with other fields, you
  535. can change the maximum length using the :attr:`~CharField.max_length` argument.
  536. ``FileField`` and ``FieldFile``
  537. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  538. .. currentmodule:: django.db.models.fields.files
  539. .. class:: FieldFile
  540. When you access a :class:`~django.db.models.FileField` on a model, you are
  541. given an instance of :class:`FieldFile` as a proxy for accessing the underlying
  542. file.
  543. The API of :class:`FieldFile` mirrors that of :class:`~django.core.files.File`,
  544. with one key difference: *The object wrapped by the class is not necessarily a
  545. wrapper around Python's built-in file object.* Instead, it is a wrapper around
  546. the result of the :attr:`Storage.open()<django.core.files.storage.Storage.open>`
  547. method, which may be a :class:`~django.core.files.File` object, or it may be a
  548. custom storage's implementation of the :class:`~django.core.files.File` API.
  549. In addition to the API inherited from
  550. :class:`~django.core.files.File` such as :meth:`~django.core.files.File.read`
  551. and :meth:`~django.core.files.File.write`, :class:`FieldFile` includes several
  552. methods that can be used to interact with the underlying file:
  553. .. warning::
  554. Two methods of this class, :meth:`~FieldFile.save` and
  555. :meth:`~FieldFile.delete`, default to saving the model object of the
  556. associated ``FieldFile`` in the database.
  557. .. attribute:: FieldFile.name
  558. The name of the file including the relative path from the root of the
  559. :class:`~django.core.files.storage.Storage` of the associated
  560. :class:`~django.db.models.FileField`.
  561. .. attribute:: FieldFile.size
  562. The result of the underlying :attr:`Storage.size()
  563. <django.core.files.storage.Storage.size>` method.
  564. .. attribute:: FieldFile.url
  565. A read-only property to access the file's relative URL by calling the
  566. :meth:`~django.core.files.storage.Storage.url` method of the underlying
  567. :class:`~django.core.files.storage.Storage` class.
  568. .. method:: FieldFile.open(mode='rb')
  569. Opens or reopens the file associated with this instance in the specified
  570. ``mode``. Unlike the standard Python ``open()`` method, it doesn't return a
  571. file descriptor.
  572. Since the underlying file is opened implicitly when accessing it, it may be
  573. unnecessary to call this method except to reset the pointer to the underlying
  574. file or to change the ``mode``.
  575. .. method:: FieldFile.close()
  576. Behaves like the standard Python ``file.close()`` method and closes the file
  577. associated with this instance.
  578. .. method:: FieldFile.save(name, content, save=True)
  579. This method takes a filename and file contents and passes them to the storage
  580. class for the field, then associates the stored file with the model field.
  581. If you want to manually associate file data with
  582. :class:`~django.db.models.FileField` instances on your model, the ``save()``
  583. method is used to persist that file data.
  584. Takes two required arguments: ``name`` which is the name of the file, and
  585. ``content`` which is an object containing the file's contents. The
  586. optional ``save`` argument controls whether or not the model instance is
  587. saved after the file associated with this field has been altered. Defaults to
  588. ``True``.
  589. Note that the ``content`` argument should be an instance of
  590. :class:`django.core.files.File`, not Python's built-in file object.
  591. You can construct a :class:`~django.core.files.File` from an existing
  592. Python file object like this::
  593. from django.core.files import File
  594. # Open an existing file using Python's built-in open()
  595. f = open('/path/to/hello.world')
  596. myfile = File(f)
  597. Or you can construct one from a Python string like this::
  598. from django.core.files.base import ContentFile
  599. myfile = ContentFile("hello world")
  600. For more information, see :doc:`/topics/files`.
  601. .. method:: FieldFile.delete(save=True)
  602. Deletes the file associated with this instance and clears all attributes on
  603. the field. Note: This method will close the file if it happens to be open when
  604. ``delete()`` is called.
  605. The optional ``save`` argument controls whether or not the model instance is
  606. saved after the file associated with this field has been deleted. Defaults to
  607. ``True``.
  608. Note that when a model is deleted, related files are not deleted. If you need
  609. to cleanup orphaned files, you'll need to handle it yourself (for instance,
  610. with a custom management command that can be run manually or scheduled to run
  611. periodically via e.g. cron).
  612. .. currentmodule:: django.db.models
  613. ``FilePathField``
  614. -----------------
  615. .. class:: FilePathField(path=None, match=None, recursive=False, max_length=100, **options)
  616. A :class:`CharField` whose choices are limited to the filenames in a certain
  617. directory on the filesystem. Has three special arguments, of which the first is
  618. **required**:
  619. .. attribute:: FilePathField.path
  620. Required. The absolute filesystem path to a directory from which this
  621. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  622. .. attribute:: FilePathField.match
  623. Optional. A regular expression, as a string, that :class:`FilePathField`
  624. will use to filter filenames. Note that the regex will be applied to the
  625. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  626. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
  627. .. attribute:: FilePathField.recursive
  628. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  629. whether all subdirectories of :attr:`~FilePathField.path` should be included
  630. .. attribute:: FilePathField.allow_files
  631. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  632. whether files in the specified location should be included. Either this or
  633. :attr:`~FilePathField.allow_folders` must be ``True``.
  634. .. attribute:: FilePathField.allow_folders
  635. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  636. whether folders in the specified location should be included. Either this
  637. or :attr:`~FilePathField.allow_files` must be ``True``.
  638. Of course, these arguments can be used together.
  639. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  640. base filename, not the full path. So, this example::
  641. FilePathField(path="/home/images", match="foo.*", recursive=True)
  642. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
  643. because the :attr:`~FilePathField.match` applies to the base filename
  644. (``foo.png`` and ``bar.png``).
  645. :class:`FilePathField` instances are created in your database as ``varchar``
  646. columns with a default max length of 100 characters. As with other fields, you
  647. can change the maximum length using the :attr:`~CharField.max_length` argument.
  648. ``FloatField``
  649. --------------
  650. .. class:: FloatField(**options)
  651. A floating-point number represented in Python by a ``float`` instance.
  652. The default form widget for this field is a :class:`~django.forms.NumberInput`
  653. when :attr:`~django.forms.Field.localize` is ``False`` or
  654. :class:`~django.forms.TextInput` otherwise.
  655. .. _floatfield_vs_decimalfield:
  656. .. admonition:: ``FloatField`` vs. ``DecimalField``
  657. The :class:`FloatField` class is sometimes mixed up with the
  658. :class:`DecimalField` class. Although they both represent real numbers, they
  659. represent those numbers differently. ``FloatField`` uses Python's ``float``
  660. type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
  661. information on the difference between the two, see Python's documentation
  662. for the :mod:`decimal` module.
  663. ``ImageField``
  664. --------------
  665. .. class:: ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
  666. Inherits all attributes and methods from :class:`FileField`, but also
  667. validates that the uploaded object is a valid image.
  668. In addition to the special attributes that are available for :class:`FileField`,
  669. an :class:`ImageField` also has ``height`` and ``width`` attributes.
  670. To facilitate querying on those attributes, :class:`ImageField` has two extra
  671. optional arguments:
  672. .. attribute:: ImageField.height_field
  673. Name of a model field which will be auto-populated with the height of the
  674. image each time the model instance is saved.
  675. .. attribute:: ImageField.width_field
  676. Name of a model field which will be auto-populated with the width of the
  677. image each time the model instance is saved.
  678. Requires the `Pillow`_ library.
  679. .. _Pillow: https://pillow.readthedocs.io/en/latest/
  680. :class:`ImageField` instances are created in your database as ``varchar``
  681. columns with a default max length of 100 characters. As with other fields, you
  682. can change the maximum length using the :attr:`~CharField.max_length` argument.
  683. The default form widget for this field is a
  684. :class:`~django.forms.ClearableFileInput`.
  685. ``IntegerField``
  686. ----------------
  687. .. class:: IntegerField(**options)
  688. An integer. Values from ``-2147483648`` to ``2147483647`` are safe in all
  689. databases supported by Django. The default form widget for this field is a
  690. :class:`~django.forms.NumberInput` when :attr:`~django.forms.Field.localize`
  691. is ``False`` or :class:`~django.forms.TextInput` otherwise.
  692. ``GenericIPAddressField``
  693. -------------------------
  694. .. class:: GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)
  695. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
  696. ``2a02:42fe::4``). The default form widget for this field is a
  697. :class:`~django.forms.TextInput`.
  698. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  699. including using the IPv4 format suggested in paragraph 3 of that section, like
  700. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  701. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  702. are converted to lowercase.
  703. .. attribute:: GenericIPAddressField.protocol
  704. Limits valid inputs to the specified protocol.
  705. Accepted values are ``'both'`` (default), ``'IPv4'``
  706. or ``'IPv6'``. Matching is case insensitive.
  707. .. attribute:: GenericIPAddressField.unpack_ipv4
  708. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  709. If this option is enabled that address would be unpacked to
  710. ``192.0.2.1``. Default is disabled. Can only be used
  711. when ``protocol`` is set to ``'both'``.
  712. If you allow for blank values, you have to allow for null values since blank
  713. values are stored as null.
  714. ``NullBooleanField``
  715. --------------------
  716. .. class:: NullBooleanField(**options)
  717. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  718. this instead of a :class:`BooleanField` with ``null=True``. The default form
  719. widget for this field is a :class:`~django.forms.NullBooleanSelect`.
  720. ``PositiveIntegerField``
  721. ------------------------
  722. .. class:: PositiveIntegerField(**options)
  723. Like an :class:`IntegerField`, but must be either positive or zero (``0``).
  724. Values from ``0`` to ``2147483647`` are safe in all databases supported by
  725. Django. The value ``0`` is accepted for backward compatibility reasons.
  726. ``PositiveSmallIntegerField``
  727. -----------------------------
  728. .. class:: PositiveSmallIntegerField(**options)
  729. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  730. (database-dependent) point. Values from ``0`` to ``32767`` are safe in all
  731. databases supported by Django.
  732. ``SlugField``
  733. -------------
  734. .. class:: SlugField(max_length=50, **options)
  735. :term:`Slug` is a newspaper term. A slug is a short label for something,
  736. containing only letters, numbers, underscores or hyphens. They're generally used
  737. in URLs.
  738. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  739. about database portability and :attr:`~CharField.max_length` in that section,
  740. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  741. default length of 50.
  742. Implies setting :attr:`Field.db_index` to ``True``.
  743. It is often useful to automatically prepopulate a SlugField based on the value
  744. of some other value. You can do this automatically in the admin using
  745. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  746. .. attribute:: SlugField.allow_unicode
  747. If ``True``, the field accepts Unicode letters in addition to ASCII
  748. letters. Defaults to ``False``.
  749. ``SmallIntegerField``
  750. ---------------------
  751. .. class:: SmallIntegerField(**options)
  752. Like an :class:`IntegerField`, but only allows values under a certain
  753. (database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all
  754. databases supported by Django.
  755. ``TextField``
  756. -------------
  757. .. class:: TextField(**options)
  758. A large text field. The default form widget for this field is a
  759. :class:`~django.forms.Textarea`.
  760. If you specify a ``max_length`` attribute, it will be reflected in the
  761. :class:`~django.forms.Textarea` widget of the auto-generated form field.
  762. However it is not enforced at the model or database level. Use a
  763. :class:`CharField` for that.
  764. .. admonition:: MySQL users
  765. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  766. collation (which is *not* the default), there are some issues to be aware
  767. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  768. details.
  769. ``TimeField``
  770. -------------
  771. .. class:: TimeField(auto_now=False, auto_now_add=False, **options)
  772. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  773. auto-population options as :class:`DateField`.
  774. The default form widget for this field is a :class:`~django.forms.TextInput`.
  775. The admin adds some JavaScript shortcuts.
  776. ``URLField``
  777. ------------
  778. .. class:: URLField(max_length=200, **options)
  779. A :class:`CharField` for a URL.
  780. The default form widget for this field is a :class:`~django.forms.TextInput`.
  781. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  782. :attr:`~CharField.max_length` argument. If you don't specify
  783. :attr:`~CharField.max_length`, a default of 200 is used.
  784. ``UUIDField``
  785. -------------
  786. .. class:: UUIDField(**options)
  787. A field for storing universally unique identifiers. Uses Python's
  788. :class:`~python:uuid.UUID` class. When used on PostgreSQL, this stores in a
  789. ``uuid`` datatype, otherwise in a ``char(32)``.
  790. Universally unique identifiers are a good alternative to :class:`AutoField` for
  791. :attr:`~Field.primary_key`. The database will not generate the UUID for you, so
  792. it is recommended to use :attr:`~Field.default`::
  793. import uuid
  794. from django.db import models
  795. class MyUUIDModel(models.Model):
  796. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  797. # other fields
  798. Note that a callable (with the parentheses omitted) is passed to ``default``,
  799. not an instance of ``UUID``.
  800. Relationship fields
  801. ===================
  802. .. module:: django.db.models.fields.related
  803. :synopsis: Related field types
  804. .. currentmodule:: django.db.models
  805. Django also defines a set of fields that represent relations.
  806. .. _ref-foreignkey:
  807. ``ForeignKey``
  808. --------------
  809. .. class:: ForeignKey(othermodel, on_delete, **options)
  810. A many-to-one relationship. Requires a positional argument: the class to which
  811. the model is related.
  812. .. _recursive-relationships:
  813. To create a recursive relationship -- an object that has a many-to-one
  814. relationship with itself -- use ``models.ForeignKey('self',
  815. on_delete=models.CASCADE)``.
  816. .. _lazy-relationships:
  817. If you need to create a relationship on a model that has not yet been defined,
  818. you can use the name of the model, rather than the model object itself::
  819. from django.db import models
  820. class Car(models.Model):
  821. manufacturer = models.ForeignKey(
  822. 'Manufacturer',
  823. on_delete=models.CASCADE,
  824. )
  825. # ...
  826. class Manufacturer(models.Model):
  827. # ...
  828. pass
  829. Relationships defined this way on :ref:`abstract models
  830. <abstract-base-classes>` are resolved when the model is subclassed as a
  831. concrete model and are not relative to the abstract model's ``app_label``:
  832. .. snippet::
  833. :filename: products/models.py
  834. from django.db import models
  835. class AbstractCar(models.Model):
  836. manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
  837. class Meta:
  838. abstract = True
  839. .. snippet::
  840. :filename: production/models.py
  841. from django.db import models
  842. from products.models import AbstractCar
  843. class Manufacturer(models.Model):
  844. pass
  845. class Car(AbstractCar):
  846. pass
  847. # Car.manufacturer will point to `production.Manufacturer` here.
  848. To refer to models defined in another application, you can explicitly specify
  849. a model with the full application label. For example, if the ``Manufacturer``
  850. model above is defined in another application called ``production``, you'd
  851. need to use::
  852. class Car(models.Model):
  853. manufacturer = models.ForeignKey(
  854. 'production.Manufacturer',
  855. on_delete=models.CASCADE,
  856. )
  857. This sort of reference can be useful when resolving circular import
  858. dependencies between two applications.
  859. A database index is automatically created on the ``ForeignKey``. You can
  860. disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
  861. avoid the overhead of an index if you are creating a foreign key for
  862. consistency rather than joins, or if you will be creating an alternative index
  863. like a partial or multiple column index.
  864. Database Representation
  865. ~~~~~~~~~~~~~~~~~~~~~~~
  866. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  867. database column name. In the above example, the database table for the ``Car``
  868. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  869. specifying :attr:`~Field.db_column`) However, your code should never have to
  870. deal with the database column name, unless you write custom SQL. You'll always
  871. deal with the field names of your model object.
  872. .. _foreign-key-arguments:
  873. Arguments
  874. ~~~~~~~~~
  875. :class:`ForeignKey` accepts other arguments that define the details of how the
  876. relation works.
  877. .. attribute:: ForeignKey.on_delete
  878. When an object referenced by a :class:`ForeignKey` is deleted, Django will
  879. emulate the behavior of the SQL constraint specified by the
  880. :attr:`on_delete` argument. For example, if you have a nullable
  881. :class:`ForeignKey` and you want it to be set null when the referenced
  882. object is deleted::
  883. user = models.ForeignKey(
  884. User,
  885. models.SET_NULL,
  886. blank=True,
  887. null=True,
  888. )
  889. The possible values for :attr:`~ForeignKey.on_delete` are found in
  890. :mod:`django.db.models`:
  891. * .. attribute:: CASCADE
  892. Cascade deletes. Django emulates the behavior of the SQL constraint ON
  893. DELETE CASCADE and also deletes the object containing the ForeignKey.
  894. * .. attribute:: PROTECT
  895. Prevent deletion of the referenced object by raising
  896. :exc:`~django.db.models.ProtectedError`, a subclass of
  897. :exc:`django.db.IntegrityError`.
  898. * .. attribute:: SET_NULL
  899. Set the :class:`ForeignKey` null; this is only possible if
  900. :attr:`~Field.null` is ``True``.
  901. * .. attribute:: SET_DEFAULT
  902. Set the :class:`ForeignKey` to its default value; a default for the
  903. :class:`ForeignKey` must be set.
  904. * .. function:: SET()
  905. Set the :class:`ForeignKey` to the value passed to
  906. :func:`~django.db.models.SET()`, or if a callable is passed in,
  907. the result of calling it. In most cases, passing a callable will be
  908. necessary to avoid executing queries at the time your models.py is
  909. imported::
  910. from django.conf import settings
  911. from django.contrib.auth import get_user_model
  912. from django.db import models
  913. def get_sentinel_user():
  914. return get_user_model().objects.get_or_create(username='deleted')[0]
  915. class MyModel(models.Model):
  916. user = models.ForeignKey(
  917. settings.AUTH_USER_MODEL,
  918. on_delete=models.SET(get_sentinel_user),
  919. )
  920. * .. attribute:: DO_NOTHING
  921. Take no action. If your database backend enforces referential
  922. integrity, this will cause an :exc:`~django.db.IntegrityError` unless
  923. you manually add an SQL ``ON DELETE`` constraint to the database field.
  924. .. attribute:: ForeignKey.limit_choices_to
  925. Sets a limit to the available choices for this field when this field is
  926. rendered using a ``ModelForm`` or the admin (by default, all objects
  927. in the queryset are available to choose). Either a dictionary, a
  928. :class:`~django.db.models.Q` object, or a callable returning a
  929. dictionary or :class:`~django.db.models.Q` object can be used.
  930. For example::
  931. staff_member = models.ForeignKey(
  932. User,
  933. on_delete=models.CASCADE,
  934. limit_choices_to={'is_staff': True},
  935. )
  936. causes the corresponding field on the ``ModelForm`` to list only ``Users``
  937. that have ``is_staff=True``. This may be helpful in the Django admin.
  938. The callable form can be helpful, for instance, when used in conjunction
  939. with the Python ``datetime`` module to limit selections by date range. For
  940. example::
  941. def limit_pub_date_choices():
  942. return {'pub_date__lte': datetime.date.utcnow()}
  943. limit_choices_to = limit_pub_date_choices
  944. If ``limit_choices_to`` is or returns a :class:`Q object
  945. <django.db.models.Q>`, which is useful for :ref:`complex queries
  946. <complex-lookups-with-q>`, then it will only have an effect on the choices
  947. available in the admin when the field is not listed in
  948. :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the
  949. ``ModelAdmin`` for the model.
  950. .. note::
  951. If a callable is used for ``limit_choices_to``, it will be invoked
  952. every time a new form is instantiated. It may also be invoked when a
  953. model is validated, for example by management commands or the admin.
  954. The admin constructs querysets to validate its form inputs in various
  955. edge cases multiple times, so there is a possibility your callable may
  956. be invoked several times.
  957. .. attribute:: ForeignKey.related_name
  958. The name to use for the relation from the related object back to this one.
  959. It's also the default value for :attr:`related_query_name` (the name to use
  960. for the reverse filter name from the target model). See the :ref:`related
  961. objects documentation <backwards-related-objects>` for a full explanation
  962. and example. Note that you must set this value when defining relations on
  963. :ref:`abstract models <abstract-base-classes>`; and when you do so
  964. :ref:`some special syntax <abstract-related-name>` is available.
  965. If you'd prefer Django not to create a backwards relation, set
  966. ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
  967. ensure that the ``User`` model won't have a backwards relation to this
  968. model::
  969. user = models.ForeignKey(
  970. User,
  971. on_delete=models.CASCADE,
  972. related_name='+',
  973. )
  974. .. attribute:: ForeignKey.related_query_name
  975. The name to use for the reverse filter name from the target model. It
  976. defaults to the value of :attr:`related_name` or
  977. :attr:`~django.db.models.Options.default_related_name` if set, otherwise it
  978. defaults to the name of the model::
  979. # Declare the ForeignKey with related_query_name
  980. class Tag(models.Model):
  981. article = models.ForeignKey(
  982. Article,
  983. on_delete=models.CASCADE,
  984. related_name="tags",
  985. related_query_name="tag",
  986. )
  987. name = models.CharField(max_length=255)
  988. # That's now the name of the reverse filter
  989. Article.objects.filter(tag__name="important")
  990. Like :attr:`related_name`, ``related_query_name`` supports app label and
  991. class interpolation via :ref:`some special syntax <abstract-related-name>`.
  992. .. attribute:: ForeignKey.to_field
  993. The field on the related object that the relation is to. By default, Django
  994. uses the primary key of the related object. If you reference a different
  995. field, that field must have ``unique=True``.
  996. .. attribute:: ForeignKey.db_constraint
  997. Controls whether or not a constraint should be created in the database for
  998. this foreign key. The default is ``True``, and that's almost certainly what
  999. you want; setting this to ``False`` can be very bad for data integrity.
  1000. That said, here are some scenarios where you might want to do this:
  1001. * You have legacy data that is not valid.
  1002. * You're sharding your database.
  1003. If this is set to ``False``, accessing a related object that doesn't exist
  1004. will raise its ``DoesNotExist`` exception.
  1005. .. attribute:: ForeignKey.swappable
  1006. Controls the migration framework's reaction if this :class:`ForeignKey`
  1007. is pointing at a swappable model. If it is ``True`` - the default -
  1008. then if the :class:`ForeignKey` is pointing at a model which matches
  1009. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  1010. model setting) the relationship will be stored in the migration using
  1011. a reference to the setting, not to the model directly.
  1012. You only want to override this to be ``False`` if you are sure your
  1013. model should always point towards the swapped-in model - for example,
  1014. if it is a profile model designed specifically for your custom user model.
  1015. Setting it to ``False`` does not mean you can reference a swappable model
  1016. even if it is swapped out - ``False`` just means that the migrations made
  1017. with this ForeignKey will always reference the exact model you specify
  1018. (so it will fail hard if the user tries to run with a User model you don't
  1019. support, for example).
  1020. If in doubt, leave it to its default of ``True``.
  1021. ``ManyToManyField``
  1022. -------------------
  1023. .. class:: ManyToManyField(othermodel, **options)
  1024. A many-to-many relationship. Requires a positional argument: the class to
  1025. which the model is related, which works exactly the same as it does for
  1026. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
  1027. :ref:`lazy <lazy-relationships>` relationships.
  1028. Related objects can be added, removed, or created with the field's
  1029. :class:`~django.db.models.fields.related.RelatedManager`.
  1030. Database Representation
  1031. ~~~~~~~~~~~~~~~~~~~~~~~
  1032. Behind the scenes, Django creates an intermediary join table to represent the
  1033. many-to-many relationship. By default, this table name is generated using the
  1034. name of the many-to-many field and the name of the table for the model that
  1035. contains it. Since some databases don't support table names above a certain
  1036. length, these table names will be automatically truncated to 64 characters and a
  1037. uniqueness hash will be used. This means you might see table names like
  1038. ``author_books_9cdf4``; this is perfectly normal. You can manually provide the
  1039. name of the join table using the :attr:`~ManyToManyField.db_table` option.
  1040. .. _manytomany-arguments:
  1041. Arguments
  1042. ~~~~~~~~~
  1043. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  1044. that control how the relationship functions.
  1045. .. attribute:: ManyToManyField.related_name
  1046. Same as :attr:`ForeignKey.related_name`.
  1047. .. attribute:: ManyToManyField.related_query_name
  1048. Same as :attr:`ForeignKey.related_query_name`.
  1049. .. attribute:: ManyToManyField.limit_choices_to
  1050. Same as :attr:`ForeignKey.limit_choices_to`.
  1051. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  1052. custom intermediate table specified using the
  1053. :attr:`~ManyToManyField.through` parameter.
  1054. .. attribute:: ManyToManyField.symmetrical
  1055. Only used in the definition of ManyToManyFields on self. Consider the
  1056. following model::
  1057. from django.db import models
  1058. class Person(models.Model):
  1059. friends = models.ManyToManyField("self")
  1060. When Django processes this model, it identifies that it has a
  1061. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  1062. ``person_set`` attribute to the ``Person`` class. Instead, the
  1063. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  1064. your friend, then you are my friend.
  1065. If you do not want symmetry in many-to-many relationships with ``self``, set
  1066. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  1067. add the descriptor for the reverse relationship, allowing
  1068. :class:`ManyToManyField` relationships to be non-symmetrical.
  1069. .. attribute:: ManyToManyField.through
  1070. Django will automatically generate a table to manage many-to-many
  1071. relationships. However, if you want to manually specify the intermediary
  1072. table, you can use the :attr:`~ManyToManyField.through` option to specify
  1073. the Django model that represents the intermediate table that you want to
  1074. use.
  1075. The most common use for this option is when you want to associate
  1076. :ref:`extra data with a many-to-many relationship
  1077. <intermediary-manytomany>`.
  1078. If you don't specify an explicit ``through`` model, there is still an
  1079. implicit ``through`` model class you can use to directly access the table
  1080. created to hold the association. It has three fields to link the models.
  1081. If the source and target models differ, the following fields are
  1082. generated:
  1083. * ``id``: the primary key of the relation.
  1084. * ``<containing_model>_id``: the ``id`` of the model that declares the
  1085. ``ManyToManyField``.
  1086. * ``<other_model>_id``: the ``id`` of the model that the
  1087. ``ManyToManyField`` points to.
  1088. If the ``ManyToManyField`` points from and to the same model, the following
  1089. fields are generated:
  1090. * ``id``: the primary key of the relation.
  1091. * ``from_<model>_id``: the ``id`` of the instance which points at the
  1092. model (i.e. the source instance).
  1093. * ``to_<model>_id``: the ``id`` of the instance to which the relationship
  1094. points (i.e. the target model instance).
  1095. This class can be used to query associated records for a given model
  1096. instance like a normal model.
  1097. .. attribute:: ManyToManyField.through_fields
  1098. Only used when a custom intermediary model is specified. Django will
  1099. normally determine which fields of the intermediary model to use in order
  1100. to establish a many-to-many relationship automatically. However,
  1101. consider the following models::
  1102. from django.db import models
  1103. class Person(models.Model):
  1104. name = models.CharField(max_length=50)
  1105. class Group(models.Model):
  1106. name = models.CharField(max_length=128)
  1107. members = models.ManyToManyField(
  1108. Person,
  1109. through='Membership',
  1110. through_fields=('group', 'person'),
  1111. )
  1112. class Membership(models.Model):
  1113. group = models.ForeignKey(Group, on_delete=models.CASCADE)
  1114. person = models.ForeignKey(Person, on_delete=models.CASCADE)
  1115. inviter = models.ForeignKey(
  1116. Person,
  1117. on_delete=models.CASCADE,
  1118. related_name="membership_invites",
  1119. )
  1120. invite_reason = models.CharField(max_length=64)
  1121. ``Membership`` has *two* foreign keys to ``Person`` (``person`` and
  1122. ``inviter``), which makes the relationship ambiguous and Django can't know
  1123. which one to use. In this case, you must explicitly specify which
  1124. foreign keys Django should use using ``through_fields``, as in the example
  1125. above.
  1126. ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where
  1127. ``field1`` is the name of the foreign key to the model the
  1128. :class:`ManyToManyField` is defined on (``group`` in this case), and
  1129. ``field2`` the name of the foreign key to the target model (``person``
  1130. in this case).
  1131. When you have more than one foreign key on an intermediary model to any
  1132. (or even both) of the models participating in a many-to-many relationship,
  1133. you *must* specify ``through_fields``. This also applies to
  1134. :ref:`recursive relationships <recursive-relationships>`
  1135. when an intermediary model is used and there are more than two
  1136. foreign keys to the model, or you want to explicitly specify which two
  1137. Django should use.
  1138. Recursive relationships using an intermediary model are always defined as
  1139. non-symmetrical -- that is, with :attr:`symmetrical=False <ManyToManyField.symmetrical>`
  1140. -- therefore, there is the concept of a "source" and a "target". In that
  1141. case ``'field1'`` will be treated as the "source" of the relationship and
  1142. ``'field2'`` as the "target".
  1143. .. attribute:: ManyToManyField.db_table
  1144. The name of the table to create for storing the many-to-many data. If this
  1145. is not provided, Django will assume a default name based upon the names of:
  1146. the table for the model defining the relationship and the name of the field
  1147. itself.
  1148. .. attribute:: ManyToManyField.db_constraint
  1149. Controls whether or not constraints should be created in the database for
  1150. the foreign keys in the intermediary table. The default is ``True``, and
  1151. that's almost certainly what you want; setting this to ``False`` can be
  1152. very bad for data integrity. That said, here are some scenarios where you
  1153. might want to do this:
  1154. * You have legacy data that is not valid.
  1155. * You're sharding your database.
  1156. It is an error to pass both ``db_constraint`` and ``through``.
  1157. .. attribute:: ManyToManyField.swappable
  1158. Controls the migration framework's reaction if this :class:`ManyToManyField`
  1159. is pointing at a swappable model. If it is ``True`` - the default -
  1160. then if the :class:`ManyToManyField` is pointing at a model which matches
  1161. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  1162. model setting) the relationship will be stored in the migration using
  1163. a reference to the setting, not to the model directly.
  1164. You only want to override this to be ``False`` if you are sure your
  1165. model should always point towards the swapped-in model - for example,
  1166. if it is a profile model designed specifically for your custom user model.
  1167. If in doubt, leave it to its default of ``True``.
  1168. :class:`ManyToManyField` does not support :attr:`~Field.validators`.
  1169. :attr:`~Field.null` has no effect since there is no way to require a
  1170. relationship at the database level.
  1171. ``OneToOneField``
  1172. -----------------
  1173. .. class:: OneToOneField(othermodel, on_delete, parent_link=False, **options)
  1174. A one-to-one relationship. Conceptually, this is similar to a
  1175. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  1176. "reverse" side of the relation will directly return a single object.
  1177. This is most useful as the primary key of a model which "extends"
  1178. another model in some way; :ref:`multi-table-inheritance` is
  1179. implemented by adding an implicit one-to-one relation from the child
  1180. model to the parent model, for example.
  1181. One positional argument is required: the class to which the model will be
  1182. related. This works exactly the same as it does for :class:`ForeignKey`,
  1183. including all the options regarding :ref:`recursive <recursive-relationships>`
  1184. and :ref:`lazy <lazy-relationships>` relationships.
  1185. If you do not specify the :attr:`~ForeignKey.related_name` argument for
  1186. the ``OneToOneField``, Django will use the lower-case name of the current model
  1187. as default value.
  1188. With the following example::
  1189. from django.conf import settings
  1190. from django.db import models
  1191. class MySpecialUser(models.Model):
  1192. user = models.OneToOneField(
  1193. settings.AUTH_USER_MODEL,
  1194. on_delete=models.CASCADE,
  1195. )
  1196. supervisor = models.OneToOneField(
  1197. settings.AUTH_USER_MODEL,
  1198. on_delete=models.CASCADE,
  1199. related_name='supervisor_of',
  1200. )
  1201. your resulting ``User`` model will have the following attributes::
  1202. >>> user = User.objects.get(pk=1)
  1203. >>> hasattr(user, 'myspecialuser')
  1204. True
  1205. >>> hasattr(user, 'supervisor_of')
  1206. True
  1207. A ``DoesNotExist`` exception is raised when accessing the reverse relationship
  1208. if an entry in the related table doesn't exist. For example, if a user doesn't
  1209. have a supervisor designated by ``MySpecialUser``::
  1210. >>> user.supervisor_of
  1211. Traceback (most recent call last):
  1212. ...
  1213. DoesNotExist: User matching query does not exist.
  1214. .. _onetoone-arguments:
  1215. Additionally, ``OneToOneField`` accepts all of the extra arguments
  1216. accepted by :class:`ForeignKey`, plus one extra argument:
  1217. .. attribute:: OneToOneField.parent_link
  1218. When ``True`` and used in a model which inherits from another
  1219. :term:`concrete model`, indicates that this field should be used as the
  1220. link back to the parent class, rather than the extra
  1221. ``OneToOneField`` which would normally be implicitly created by
  1222. subclassing.
  1223. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
  1224. examples of ``OneToOneField``.
  1225. Field API reference
  1226. ===================
  1227. .. class:: Field
  1228. ``Field`` is an abstract class that represents a database table column.
  1229. Django uses fields to create the database table (:meth:`db_type`), to map
  1230. Python types to database (:meth:`get_prep_value`) and vice-versa
  1231. (:meth:`from_db_value`).
  1232. A field is thus a fundamental piece in different Django APIs, notably,
  1233. :class:`models <django.db.models.Model>` and :class:`querysets
  1234. <django.db.models.query.QuerySet>`.
  1235. In models, a field is instantiated as a class attribute and represents a
  1236. particular table column, see :doc:`/topics/db/models`. It has attributes
  1237. such as :attr:`null` and :attr:`unique`, and methods that Django uses to
  1238. map the field value to database-specific values.
  1239. A ``Field`` is a subclass of
  1240. :class:`~django.db.models.lookups.RegisterLookupMixin` and thus both
  1241. :class:`~django.db.models.Transform` and
  1242. :class:`~django.db.models.Lookup` can be registered on it to be used
  1243. in ``QuerySet``\s (e.g. ``field_name__exact="foo"``). All :ref:`built-in
  1244. lookups <field-lookups>` are registered by default.
  1245. All of Django's built-in fields, such as :class:`CharField`, are particular
  1246. implementations of ``Field``. If you need a custom field, you can either
  1247. subclass any of the built-in fields or write a ``Field`` from scratch. In
  1248. either case, see :doc:`/howto/custom-model-fields`.
  1249. .. attribute:: description
  1250. A verbose description of the field, e.g. for the
  1251. :mod:`django.contrib.admindocs` application.
  1252. The description can be of the form::
  1253. description = _("String (up to %(max_length)s)")
  1254. where the arguments are interpolated from the field's ``__dict__``.
  1255. To map a ``Field`` to a database-specific type, Django exposes several
  1256. methods:
  1257. .. method:: get_internal_type()
  1258. Returns a string naming this field for backend specific purposes.
  1259. By default, it returns the class name.
  1260. See :ref:`emulating-built-in-field-types` for usage in custom fields.
  1261. .. method:: db_type(connection)
  1262. Returns the database column data type for the :class:`Field`, taking
  1263. into account the ``connection``.
  1264. See :ref:`custom-database-types` for usage in custom fields.
  1265. .. method:: rel_db_type(connection)
  1266. Returns the database column data type for fields such as ``ForeignKey``
  1267. and ``OneToOneField`` that point to the :class:`Field`, taking
  1268. into account the ``connection``.
  1269. See :ref:`custom-database-types` for usage in custom fields.
  1270. There are three main situations where Django needs to interact with the
  1271. database backend and fields:
  1272. * when it queries the database (Python value -> database backend value)
  1273. * when it loads data from the database (database backend value -> Python
  1274. value)
  1275. * when it saves to the database (Python value -> database backend value)
  1276. When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used:
  1277. .. method:: get_prep_value(value)
  1278. ``value`` is the current value of the model's attribute, and the method
  1279. should return data in a format that has been prepared for use as a
  1280. parameter in a query.
  1281. See :ref:`converting-python-objects-to-query-values` for usage.
  1282. .. method:: get_db_prep_value(value, connection, prepared=False)
  1283. Converts ``value`` to a backend-specific value. By default it returns
  1284. ``value`` if ``prepared=True`` and :meth:`~Field.get_prep_value` if is
  1285. ``False``.
  1286. See :ref:`converting-query-values-to-database-values` for usage.
  1287. When loading data, :meth:`from_db_value` is used:
  1288. .. method:: from_db_value(value, expression, connection, context)
  1289. Converts a value as returned by the database to a Python object. It is
  1290. the reverse of :meth:`get_prep_value`.
  1291. This method is not used for most built-in fields as the database
  1292. backend already returns the correct Python type, or the backend itself
  1293. does the conversion.
  1294. See :ref:`converting-values-to-python-objects` for usage.
  1295. .. note::
  1296. For performance reasons, ``from_db_value`` is not implemented as a
  1297. no-op on fields which do not require it (all Django fields).
  1298. Consequently you may not call ``super`` in your definition.
  1299. When saving, :meth:`pre_save` and :meth:`get_db_prep_save` are used:
  1300. .. method:: get_db_prep_save(value, connection)
  1301. Same as the :meth:`get_db_prep_value`, but called when the field value
  1302. must be *saved* to the database. By default returns
  1303. :meth:`get_db_prep_value`.
  1304. .. method:: pre_save(model_instance, add)
  1305. Method called prior to :meth:`get_db_prep_save` to prepare the value
  1306. before being saved (e.g. for :attr:`DateField.auto_now`).
  1307. ``model_instance`` is the instance this field belongs to and ``add``
  1308. is whether the instance is being saved to the database for the first
  1309. time.
  1310. It should return the value of the appropriate attribute from
  1311. ``model_instance`` for this field. The attribute name is in
  1312. ``self.attname`` (this is set up by :class:`~django.db.models.Field`).
  1313. See :ref:`preprocessing-values-before-saving` for usage.
  1314. Fields often receive their values as a different type, either from
  1315. serialization or from forms.
  1316. .. method:: to_python(value)
  1317. Converts the value into the correct Python object. It acts as the
  1318. reverse of :meth:`value_to_string`, and is also called in
  1319. :meth:`~django.db.models.Model.clean`.
  1320. See :ref:`converting-values-to-python-objects` for usage.
  1321. Besides saving to the database, the field also needs to know how to
  1322. serialize its value:
  1323. .. method:: value_to_string(obj)
  1324. Converts ``obj`` to a string. Used to serialize the value of the field.
  1325. See :ref:`converting-model-field-to-serialization` for usage.
  1326. When using :class:`model forms <django.forms.ModelForm>`, the ``Field``
  1327. needs to know which form field it should be represented by:
  1328. .. method:: formfield(form_class=None, choices_form_class=None, **kwargs)
  1329. Returns the default :class:`django.forms.Field` of this field for
  1330. :class:`~django.forms.ModelForm`.
  1331. By default, if both ``form_class`` and ``choices_form_class`` are
  1332. ``None``, it uses :class:`~django.forms.CharField`. If the field has
  1333. :attr:`~django.db.models.Field.choices` and ``choices_form_class``
  1334. isn't specified, it uses :class:`~django.forms.TypedChoiceField`.
  1335. See :ref:`specifying-form-field-for-model-field` for usage.
  1336. .. method:: deconstruct()
  1337. Returns a 4-tuple with enough information to recreate the field:
  1338. 1. The name of the field on the model.
  1339. 2. The import path of the field (e.g. ``"django.db.models.IntegerField"``).
  1340. This should be the most portable version, so less specific may be better.
  1341. 3. A list of positional arguments.
  1342. 4. A dict of keyword arguments.
  1343. This method must be added to fields prior to 1.7 to migrate its data
  1344. using :doc:`/topics/migrations`.
  1345. .. _model-field-attributes:
  1346. =========================
  1347. Field attribute reference
  1348. =========================
  1349. Every ``Field`` instance contains several attributes that allow
  1350. introspecting its behavior. Use these attributes instead of ``isinstance``
  1351. checks when you need to write code that depends on a field's functionality.
  1352. These attributes can be used together with the :ref:`Model._meta API
  1353. <model-meta-field-api>` to narrow down a search for specific field types.
  1354. Custom model fields should implement these flags.
  1355. Attributes for fields
  1356. =====================
  1357. .. attribute:: Field.auto_created
  1358. Boolean flag that indicates if the field was automatically created, such
  1359. as the ``OneToOneField`` used by model inheritance.
  1360. .. attribute:: Field.concrete
  1361. Boolean flag that indicates if the field has a database column associated
  1362. with it.
  1363. .. attribute:: Field.hidden
  1364. Boolean flag that indicates if a field is used to back another non-hidden
  1365. field's functionality (e.g. the ``content_type`` and ``object_id`` fields
  1366. that make up a ``GenericForeignKey``). The ``hidden`` flag is used to
  1367. distinguish what constitutes the public subset of fields on the model from
  1368. all the fields on the model.
  1369. .. note::
  1370. :meth:`Options.get_fields()
  1371. <django.db.models.options.Options.get_fields()>`
  1372. excludes hidden fields by default. Pass in ``include_hidden=True`` to
  1373. return hidden fields in the results.
  1374. .. attribute:: Field.is_relation
  1375. Boolean flag that indicates if a field contains references to one or
  1376. more other models for its functionality (e.g. ``ForeignKey``,
  1377. ``ManyToManyField``, ``OneToOneField``, etc.).
  1378. .. attribute:: Field.model
  1379. Returns the model on which the field is defined. If a field is defined on
  1380. a superclass of a model, ``model`` will refer to the superclass, not the
  1381. class of the instance.
  1382. Attributes for fields with relations
  1383. ====================================
  1384. These attributes are used to query for the cardinality and other details of a
  1385. relation. These attribute are present on all fields; however, they will only
  1386. have boolean values (rather than ``None``) if the field is a relation type
  1387. (:attr:`Field.is_relation=True <Field.is_relation>`).
  1388. .. attribute:: Field.many_to_many
  1389. Boolean flag that is ``True`` if the field has a many-to-many relation;
  1390. ``False`` otherwise. The only field included with Django where this is
  1391. ``True`` is ``ManyToManyField``.
  1392. .. attribute:: Field.many_to_one
  1393. Boolean flag that is ``True`` if the field has a many-to-one relation, such
  1394. as a ``ForeignKey``; ``False`` otherwise.
  1395. .. attribute:: Field.one_to_many
  1396. Boolean flag that is ``True`` if the field has a one-to-many relation, such
  1397. as a ``GenericRelation`` or the reverse of a ``ForeignKey``; ``False``
  1398. otherwise.
  1399. .. attribute:: Field.one_to_one
  1400. Boolean flag that is ``True`` if the field has a one-to-one relation, such
  1401. as a ``OneToOneField``; ``False`` otherwise.
  1402. .. attribute:: Field.related_model
  1403. Points to the model the field relates to. For example, ``Author`` in
  1404. ``ForeignKey(Author, on_delete=models.CASCADE)``. The ``related_model`` for
  1405. a ``GenericForeignKey`` is always ``None``.