fields.txt 87 KB

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