fields.txt 68 KB

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