fields.txt 74 KB

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