fields.txt 88 KB

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