fields.txt 88 KB

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