fields.txt 73 KB

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