fields.txt 69 KB

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