fields.txt 80 KB

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