fields.txt 93 KB

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