2
0

fields.txt 96 KB

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