2
0

fields.txt 93 KB

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