fields.txt 87 KB

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