fields.txt 72 KB

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