fields.txt 74 KB

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