fields.txt 97 KB

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