fields.txt 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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 gory details about all the `field options`_ and
  8. `field types`_ Django's got to offer.
  9. .. seealso::
  10. If the built-in fields don't do the trick, you can try :doc:`localflavor
  11. </topics/localflavor>`, which contains assorted pieces of code
  12. that are useful for particular countries or cultures. Also, you can easily
  13. :doc:`write your own custom model fields </howto/custom-model-fields>`.
  14. .. note::
  15. Technically, these models are defined in :mod:`django.db.models.fields`, but
  16. for convenience they're imported into :mod:`django.db.models`; the standard
  17. convention is to use ``from django.db import models`` and refer to fields as
  18. ``models.<Foo>Field``.
  19. .. _common-model-field-options:
  20. Field options
  21. =============
  22. The following arguments are available to all field types. All are optional.
  23. ``null``
  24. --------
  25. .. attribute:: Field.null
  26. If ``True``, Django will store empty values as ``NULL`` in the database. Default
  27. is ``False``.
  28. Avoid using :attr:`~Field.null` on string-based fields such as
  29. :class:`CharField` and :class:`TextField` because empty string values will
  30. always be stored as empty strings, not as ``NULL``. If a string-based field has
  31. ``null=True``, that means it has two possible values for "no data": ``NULL``,
  32. and the empty string. In most cases, it's redundant to have two possible values
  33. for "no data;" the Django convention is to use the empty string, not ``NULL``.
  34. For both string-based and non-string-based fields, you will also need to
  35. set ``blank=True`` if you wish to permit empty values in forms, as the
  36. :attr:`~Field.null` parameter only affects database storage
  37. (see :attr:`~Field.blank`).
  38. .. note::
  39. When using the Oracle database backend, the value ``NULL`` will be stored to
  40. denote the empty string regardless of this attribute.
  41. If you want to accept :attr:`~Field.null` values with :class:`BooleanField`,
  42. use :class:`NullBooleanField` instead.
  43. ``blank``
  44. ---------
  45. .. attribute:: Field.blank
  46. If ``True``, the field is allowed to be blank. Default is ``False``.
  47. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  48. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  49. a field has ``blank=True``, form validation will allow entry of an empty value.
  50. If a field has ``blank=False``, the field will be required.
  51. .. _field-choices:
  52. ``choices``
  53. -----------
  54. .. attribute:: Field.choices
  55. An iterable (e.g., a list or tuple) consisting itself of iterables of exactly
  56. two items (e.g. ``[(A, B), (A, B) ...]``) to use as choices for this field. If
  57. this is given, the default form widget will be a select box with these choices
  58. instead of the standard text field.
  59. The first element in each tuple is the actual value to be stored, and the
  60. second element is the human-readable name. For example::
  61. YEAR_IN_SCHOOL_CHOICES = (
  62. ('FR', 'Freshman'),
  63. ('SO', 'Sophomore'),
  64. ('JR', 'Junior'),
  65. ('SR', 'Senior'),
  66. )
  67. Generally, it's best to define choices inside a model class, and to
  68. define a suitably-named constant for each value::
  69. from django.db import models
  70. class Student(models.Model):
  71. FRESHMAN = 'FR'
  72. SOPHOMORE = 'SO'
  73. JUNIOR = 'JR'
  74. SENIOR = 'SR'
  75. YEAR_IN_SCHOOL_CHOICES = (
  76. (FRESHMAN, 'Freshman'),
  77. (SOPHOMORE, 'Sophomore'),
  78. (JUNIOR, 'Junior'),
  79. (SENIOR, 'Senior'),
  80. )
  81. year_in_school = models.CharField(max_length=2,
  82. choices=YEAR_IN_SCHOOL_CHOICES,
  83. default=FRESHMAN)
  84. def is_upperclass(self):
  85. return self.year_in_school in (self.JUNIOR, self.SENIOR)
  86. Though you can define a choices list outside of a model class and then
  87. refer to it, defining the choices and names for each choice inside the
  88. model class keeps all of that information with the class that uses it,
  89. and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
  90. will work anywhere that the ``Student`` model has been imported).
  91. You can also collect your available choices into named groups that can
  92. be used for organizational purposes::
  93. MEDIA_CHOICES = (
  94. ('Audio', (
  95. ('vinyl', 'Vinyl'),
  96. ('cd', 'CD'),
  97. )
  98. ),
  99. ('Video', (
  100. ('vhs', 'VHS Tape'),
  101. ('dvd', 'DVD'),
  102. )
  103. ),
  104. ('unknown', 'Unknown'),
  105. )
  106. The first element in each tuple is the name to apply to the group. The
  107. second element is an iterable of 2-tuples, with each 2-tuple containing
  108. a value and a human-readable name for an option. Grouped options may be
  109. combined with ungrouped options within a single list (such as the
  110. `unknown` option in this example).
  111. For each model field that has :attr:`~Field.choices` set, Django will add a
  112. method to retrieve the human-readable name for the field's current value. See
  113. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  114. documentation.
  115. Note that choices can be any iterable object -- not necessarily a list or tuple.
  116. This lets you construct choices dynamically. But if you find yourself hacking
  117. :attr:`~Field.choices` to be dynamic, you're probably better off using a proper
  118. database table with a :class:`ForeignKey`. :attr:`~Field.choices` is meant for
  119. static data that doesn't change much, if ever.
  120. .. versionadded:: 1.7
  121. Unless :attr:`blank=False<Field.blank>` is set on the field along with a
  122. :attr:`~Field.default` then a label containing ``"---------"`` will be rendered
  123. with the select box. To override this behavior, add a tuple to ``choices``
  124. containing ``None``; e.g. ``(None, 'Your String For Display')``.
  125. Alternatively, you can use an empty string instead of ``None`` where this makes
  126. sense - such as on a :class:`~django.db.models.CharField`.
  127. ``db_column``
  128. -------------
  129. .. attribute:: Field.db_column
  130. The name of the database column to use for this field. If this isn't given,
  131. Django will use the field's name.
  132. If your database column name is an SQL reserved word, or contains
  133. characters that aren't allowed in Python variable names -- notably, the
  134. hyphen -- that's OK. Django quotes column and table names behind the
  135. scenes.
  136. ``db_index``
  137. ------------
  138. .. attribute:: Field.db_index
  139. If ``True``, :djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a
  140. ``CREATE INDEX`` statement for this field.
  141. ``db_tablespace``
  142. -----------------
  143. .. attribute:: Field.db_tablespace
  144. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  145. this field's index, if this field is indexed. The default is the project's
  146. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
  147. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
  148. support tablespaces for indexes, this option is ignored.
  149. ``default``
  150. -----------
  151. .. attribute:: Field.default
  152. The default value for the field. This can be a value or a callable object. If
  153. callable it will be called every time a new object is created.
  154. The default cannot be a mutable object (model instance, list, set, etc.), as a
  155. reference to the same instance of that object would be used as the default
  156. value in all new model instances. Instead, wrap the desired default in a
  157. callable. For example, if you had a custom ``JSONField`` and wanted to specify
  158. a dictionary as the default, use a ``lambda`` as follows::
  159. contact_info = JSONField("ContactInfo", default=lambda:{"email": "to1@example.com"})
  160. ``editable``
  161. ------------
  162. .. attribute:: Field.editable
  163. If ``False``, the field will not be displayed in the admin or any other
  164. :class:`~django.forms.ModelForm`. Default is ``True``.
  165. ``error_messages``
  166. ------------------
  167. .. attribute:: Field.error_messages
  168. The ``error_messages`` argument lets you override the default messages that the
  169. field will raise. Pass in a dictionary with keys matching the error messages you
  170. want to override.
  171. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  172. ``unique``, and ``unique_for_date``. Additional error message keys are
  173. specified for each field in the `Field types`_ section below.
  174. .. versionadded:: 1.7
  175. The ``unique_for_date`` error message key was added.
  176. ``help_text``
  177. -------------
  178. .. attribute:: Field.help_text
  179. Extra "help" text to be displayed with the form widget. It's useful for
  180. documentation even if your field isn't used on a form.
  181. Note that this value is *not* HTML-escaped in automatically-generated
  182. forms. This lets you include HTML in :attr:`~Field.help_text` if you so
  183. desire. For example::
  184. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  185. Alternatively you can use plain text and
  186. ``django.utils.html.escape()`` to escape any HTML special characters.
  187. ``primary_key``
  188. ---------------
  189. .. attribute:: Field.primary_key
  190. If ``True``, this field is the primary key for the model.
  191. If you don't specify ``primary_key=True`` for any field in your model, Django
  192. will automatically add an :class:`AutoField` to hold the primary key, so you
  193. don't need to set ``primary_key=True`` on any of your fields unless you want to
  194. override the default primary-key behavior. For more, see
  195. :ref:`automatic-primary-key-fields`.
  196. ``primary_key=True`` implies :attr:`null=False <Field.null>` and :attr:`unique=True <Field.unique>`.
  197. Only one primary key is allowed on an object.
  198. ``unique``
  199. ----------
  200. .. attribute:: Field.unique
  201. If ``True``, this field must be unique throughout the table.
  202. This is enforced at the database level and by model validation. If
  203. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  204. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  205. :meth:`~django.db.models.Model.save` method.
  206. This option is valid on all field types except :class:`ManyToManyField`,
  207. :class:`OneToOneField`, and :class:`FileField`.
  208. Note that when ``unique`` is ``True``, you don't need to specify
  209. :attr:`~Field.db_index`, because ``unique`` implies the creation of an index.
  210. ``unique_for_date``
  211. -------------------
  212. .. attribute:: Field.unique_for_date
  213. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  214. require that this field be unique for the value of the date field.
  215. For example, if you have a field ``title`` that has
  216. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  217. records with the same ``title`` and ``pub_date``.
  218. Note that if you set this to point to a :class:`DateTimeField`, only the date
  219. portion of the field will be considered. Besides, when :setting:`USE_TZ` is
  220. ``True``, the check will be performed in the :ref:`current time zone
  221. <default-current-time-zone>` at the time the object gets saved.
  222. This is enforced by :meth:`Model.validate_unique()` during model validation
  223. but not at the database level. If any :attr:`~Field.unique_for_date` constraint
  224. involves fields that are not part of a :class:`~django.forms.ModelForm` (for
  225. example, if one of the fields is listed in ``exclude`` or has
  226. :attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
  227. skip validation for that particular constraint.
  228. ``unique_for_month``
  229. --------------------
  230. .. attribute:: Field.unique_for_month
  231. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  232. respect to the month.
  233. ``unique_for_year``
  234. -------------------
  235. .. attribute:: Field.unique_for_year
  236. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  237. ``verbose_name``
  238. -------------------
  239. .. attribute:: Field.verbose_name
  240. A human-readable name for the field. If the verbose name isn't given, Django
  241. will automatically create it using the field's attribute name, converting
  242. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
  243. ``validators``
  244. -------------------
  245. .. attribute:: Field.validators
  246. A list of validators to run for this field. See the :doc:`validators
  247. documentation </ref/validators>` for more information.
  248. Registering and fetching lookups
  249. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  250. ``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.
  251. The API can be used to customize which lookups are available for a field class, and
  252. how lookups are fetched from a field.
  253. .. _model-field-types:
  254. Field types
  255. ===========
  256. .. currentmodule:: django.db.models
  257. ``AutoField``
  258. -------------
  259. .. class:: AutoField(**options)
  260. An :class:`IntegerField` that automatically increments
  261. according to available IDs. You usually won't need to use this directly; a
  262. primary key field will automatically be added to your model if you don't specify
  263. otherwise. See :ref:`automatic-primary-key-fields`.
  264. ``BigIntegerField``
  265. -------------------
  266. .. class:: BigIntegerField([**options])
  267. A 64 bit integer, much like an :class:`IntegerField` except that it is
  268. guaranteed to fit numbers from ``-9223372036854775808`` to
  269. ``9223372036854775807``. The default form widget for this field is a
  270. :class:`~django.forms.TextInput`.
  271. ``BinaryField``
  272. -------------------
  273. .. class:: BinaryField([**options])
  274. .. versionadded:: 1.6
  275. A field to store raw binary data. It only supports ``bytes`` assignment. Be
  276. aware that this field has limited functionality. For example, it is not possible
  277. to filter a queryset on a ``BinaryField`` value.
  278. .. admonition:: Abusing ``BinaryField``
  279. Although you might think about storing files in the database, consider that
  280. it is bad design in 99% of the cases. This field is *not* a replacement for
  281. proper :doc:`static files </howto/static-files/index>` handling.
  282. ``BooleanField``
  283. ----------------
  284. .. class:: BooleanField(**options)
  285. A true/false field.
  286. The default form widget for this field is a
  287. :class:`~django.forms.CheckboxInput`.
  288. If you need to accept :attr:`~Field.null` values then use
  289. :class:`NullBooleanField` instead.
  290. .. versionchanged:: 1.6
  291. The default value of ``BooleanField`` was changed from ``False`` to
  292. ``None`` when :attr:`Field.default` isn't defined.
  293. ``CharField``
  294. -------------
  295. .. class:: CharField(max_length=None, [**options])
  296. A string field, for small- to large-sized strings.
  297. For large amounts of text, use :class:`~django.db.models.TextField`.
  298. The default form widget for this field is a :class:`~django.forms.TextInput`.
  299. :class:`CharField` has one extra required argument:
  300. .. attribute:: CharField.max_length
  301. The maximum length (in characters) of the field. The max_length is enforced
  302. at the database level and in Django's validation.
  303. .. note::
  304. If you are writing an application that must be portable to multiple
  305. database backends, you should be aware that there are restrictions on
  306. ``max_length`` for some backends. Refer to the :doc:`database backend
  307. notes </ref/databases>` for details.
  308. .. admonition:: MySQL users
  309. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  310. collation (which is *not* the default), there are some issues to be aware
  311. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  312. details.
  313. ``CommaSeparatedIntegerField``
  314. ------------------------------
  315. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  316. A field of integers separated by commas. As in :class:`CharField`, the
  317. :attr:`~CharField.max_length` argument is required and the note about database
  318. portability mentioned there should be heeded.
  319. ``DateField``
  320. -------------
  321. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  322. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  323. optional arguments:
  324. .. attribute:: DateField.auto_now
  325. Automatically set the field to now every time the object is saved. Useful
  326. for "last-modified" timestamps. Note that the current date is *always*
  327. used; it's not just a default value that you can override.
  328. .. attribute:: DateField.auto_now_add
  329. Automatically set the field to now when the object is first created. Useful
  330. for creation of timestamps. Note that the current date is *always* used;
  331. it's not just a default value that you can override.
  332. The default form widget for this field is a
  333. :class:`~django.forms.TextInput`. The admin adds a JavaScript calendar,
  334. and a shortcut for "Today". Includes an additional ``invalid_date`` error
  335. message key.
  336. .. note::
  337. As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
  338. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  339. set.
  340. ``DateTimeField``
  341. -----------------
  342. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  343. A date and time, represented in Python by a ``datetime.datetime`` instance.
  344. Takes the same extra arguments as :class:`DateField`.
  345. The default form widget for this field is a single
  346. :class:`~django.forms.TextInput`. The admin uses two separate
  347. :class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
  348. ``DecimalField``
  349. ----------------
  350. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  351. A fixed-precision decimal number, represented in Python by a
  352. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  353. .. attribute:: DecimalField.max_digits
  354. The maximum number of digits allowed in the number. Note that this number
  355. must be greater than or equal to ``decimal_places``.
  356. .. attribute:: DecimalField.decimal_places
  357. The number of decimal places to store with the number.
  358. For example, to store numbers up to ``999`` with a resolution of 2 decimal
  359. places, you'd use::
  360. models.DecimalField(..., max_digits=5, decimal_places=2)
  361. And to store numbers up to approximately one billion with a resolution of 10
  362. decimal places::
  363. models.DecimalField(..., max_digits=19, decimal_places=10)
  364. The default form widget for this field is a :class:`~django.forms.TextInput`.
  365. .. note::
  366. For more information about the differences between the
  367. :class:`FloatField` and :class:`DecimalField` classes, please
  368. see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`.
  369. ``EmailField``
  370. --------------
  371. .. class:: EmailField([max_length=75, **options])
  372. A :class:`CharField` that checks that the value is a valid email address.
  373. .. admonition:: Incompliance to RFCs
  374. The default 75 character ``max_length`` is not capable of storing all
  375. possible RFC3696/5321-compliant email addresses. In order to store all
  376. possible valid email addresses, a ``max_length`` of 254 is required.
  377. The default ``max_length`` of 75 exists for historical reasons. The
  378. default has not been changed in order to maintain backwards
  379. compatibility with existing uses of :class:`EmailField`.
  380. ``FileField``
  381. -------------
  382. .. class:: FileField([upload_to=None, max_length=100, **options])
  383. A file-upload field.
  384. .. note::
  385. The ``primary_key`` and ``unique`` arguments are not supported, and will
  386. raise a ``TypeError`` if used.
  387. Has two optional arguments:
  388. .. attribute:: FileField.upload_to
  389. .. versionchanged:: 1.7
  390. ``upload_to`` was required in older versions of Django.
  391. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  392. setting to determine the value of the
  393. :attr:`~django.db.models.fields.files.FieldFile.url` attribute.
  394. This path may contain :func:`~time.strftime` formatting, which will be
  395. replaced by the date/time of the file upload (so that uploaded files don't
  396. fill up the given directory).
  397. This may also be a callable, such as a function, which will be called to
  398. obtain the upload path, including the filename. This callable must be able
  399. to accept two arguments, and return a Unix-style path (with forward slashes)
  400. to be passed along to the storage system. The two arguments that will be
  401. passed are:
  402. ====================== ===============================================
  403. Argument Description
  404. ====================== ===============================================
  405. ``instance`` An instance of the model where the
  406. ``FileField`` is defined. More specifically,
  407. this is the particular instance where the
  408. current file is being attached.
  409. In most cases, this object will not have been
  410. saved to the database yet, so if it uses the
  411. default ``AutoField``, *it might not yet have a
  412. value for its primary key field*.
  413. ``filename`` The filename that was originally given to the
  414. file. This may or may not be taken into account
  415. when determining the final destination path.
  416. ====================== ===============================================
  417. .. attribute:: FileField.storage
  418. A storage object, which handles the storage and retrieval of your
  419. files. See :doc:`/topics/files` for details on how to provide this object.
  420. The default form widget for this field is a
  421. :class:`~django.forms.ClearableFileInput`.
  422. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  423. takes a few steps:
  424. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  425. full path to a directory where you'd like Django to store uploaded files.
  426. (For performance, these files are not stored in the database.) Define
  427. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  428. that this directory is writable by the Web server's user account.
  429. 2. Add the :class:`FileField` or :class:`ImageField` to your model, defining
  430. the :attr:`~FileField.upload_to` option to specify a subdirectory of
  431. :setting:`MEDIA_ROOT` to use for uploaded files.
  432. 3. All that will be stored in your database is a path to the file
  433. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  434. convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
  435. provided by Django. For example, if your :class:`ImageField` is called
  436. ``mug_shot``, you can get the absolute path to your image in a template with
  437. ``{{ object.mug_shot.url }}``.
  438. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  439. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  440. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
  441. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
  442. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
  443. the directory ``/home/media/photos/2007/01/15``.
  444. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
  445. size, you could use the :attr:`~django.core.files.File.name` and
  446. :attr:`~django.core.files.File.size` attributes respectively; for more
  447. information on the available attributes and methods, see the
  448. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
  449. topic guide.
  450. .. note::
  451. The file is saved as part of saving the model in the database, so the actual
  452. file name used on disk cannot be relied on until after the model has been
  453. saved.
  454. The uploaded file's relative URL can be obtained using the
  455. :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
  456. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
  457. underlying :class:`~django.core.files.storage.Storage` class.
  458. .. _file-upload-security:
  459. Note that whenever you deal with uploaded files, you should pay close attention
  460. to where you're uploading them and what type of files they are, to avoid
  461. security holes. *Validate all uploaded files* so that you're sure the files are
  462. what you think they are. For example, if you blindly let somebody upload files,
  463. without validation, to a directory that's within your Web server's document
  464. root, then somebody could upload a CGI or PHP script and execute that script by
  465. visiting its URL on your site. Don't allow that.
  466. Also note that even an uploaded HTML file, since it can be executed by the
  467. browser (though not by the server), can pose security threats that are
  468. equivalent to XSS or CSRF attacks.
  469. By default, :class:`FileField` instances are
  470. created as ``varchar(100)`` columns in your database. As with other fields, you
  471. can change the maximum length using the :attr:`~CharField.max_length` argument.
  472. FileField and FieldFile
  473. ~~~~~~~~~~~~~~~~~~~~~~~
  474. .. currentmodule:: django.db.models.fields.files
  475. .. class:: FieldFile
  476. When you access a :class:`~django.db.models.FileField` on a model, you are
  477. given an instance of :class:`FieldFile` as a proxy for accessing the underlying
  478. file. This class has several attributes and methods that can be used to
  479. interact with file data:
  480. .. attribute:: FieldFile.url
  481. A read-only property to access the file's relative URL by calling the
  482. :meth:`~django.core.files.storage.Storage.url` method of the underlying
  483. :class:`~django.core.files.storage.Storage` class.
  484. .. method:: FieldFile.open(mode='rb')
  485. Behaves like the standard Python ``open()`` method and opens the file
  486. associated with this instance in the mode specified by ``mode``.
  487. .. method:: FieldFile.close()
  488. Behaves like the standard Python ``file.close()`` method and closes the file
  489. associated with this instance.
  490. .. method:: FieldFile.save(name, content, save=True)
  491. This method takes a filename and file contents and passes them to the storage
  492. class for the field, then associates the stored file with the model field.
  493. If you want to manually associate file data with
  494. :class:`~django.db.models.FileField` instances on your model, the ``save()``
  495. method is used to persist that file data.
  496. Takes two required arguments: ``name`` which is the name of the file, and
  497. ``content`` which is an object containing the file's contents. The
  498. optional ``save`` argument controls whether or not the instance is
  499. saved after the file has been altered. Defaults to ``True``.
  500. Note that the ``content`` argument should be an instance of
  501. :class:`django.core.files.File`, not Python's built-in file object.
  502. You can construct a :class:`~django.core.files.File` from an existing
  503. Python file object like this::
  504. from django.core.files import File
  505. # Open an existing file using Python's built-in open()
  506. f = open('/tmp/hello.world')
  507. myfile = File(f)
  508. Or you can construct one from a Python string like this::
  509. from django.core.files.base import ContentFile
  510. myfile = ContentFile("hello world")
  511. For more information, see :doc:`/topics/files`.
  512. .. method:: FieldFile.delete(save=True)
  513. Deletes the file associated with this instance and clears all attributes on
  514. the field. Note: This method will close the file if it happens to be open when
  515. ``delete()`` is called.
  516. The optional ``save`` argument controls whether or not the instance is saved
  517. after the file has been deleted. Defaults to ``True``.
  518. Note that when a model is deleted, related files are not deleted. If you need
  519. to cleanup orphaned files, you'll need to handle it yourself (for instance,
  520. with a custom management command that can be run manually or scheduled to run
  521. periodically via e.g. cron).
  522. .. currentmodule:: django.db.models
  523. ``FilePathField``
  524. -----------------
  525. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  526. A :class:`CharField` whose choices are limited to the filenames in a certain
  527. directory on the filesystem. Has three special arguments, of which the first is
  528. **required**:
  529. .. attribute:: FilePathField.path
  530. Required. The absolute filesystem path to a directory from which this
  531. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  532. .. attribute:: FilePathField.match
  533. Optional. A regular expression, as a string, that :class:`FilePathField`
  534. will use to filter filenames. Note that the regex will be applied to the
  535. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  536. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
  537. .. attribute:: FilePathField.recursive
  538. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  539. whether all subdirectories of :attr:`~FilePathField.path` should be included
  540. .. attribute:: FilePathField.allow_files
  541. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  542. whether files in the specified location should be included. Either this or
  543. :attr:`~FilePathField.allow_folders` must be ``True``.
  544. .. attribute:: FilePathField.allow_folders
  545. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  546. whether folders in the specified location should be included. Either this
  547. or :attr:`~FilePathField.allow_files` must be ``True``.
  548. Of course, these arguments can be used together.
  549. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  550. base filename, not the full path. So, this example::
  551. FilePathField(path="/home/images", match="foo.*", recursive=True)
  552. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
  553. because the :attr:`~FilePathField.match` applies to the base filename
  554. (``foo.png`` and ``bar.png``).
  555. By default, :class:`FilePathField` instances are
  556. created as ``varchar(100)`` columns in your database. As with other fields, you
  557. can change the maximum length using the :attr:`~CharField.max_length` argument.
  558. ``FloatField``
  559. --------------
  560. .. class:: FloatField([**options])
  561. A floating-point number represented in Python by a ``float`` instance.
  562. The default form widget for this field is a :class:`~django.forms.TextInput`.
  563. .. _floatfield_vs_decimalfield:
  564. .. admonition:: ``FloatField`` vs. ``DecimalField``
  565. The :class:`FloatField` class is sometimes mixed up with the
  566. :class:`DecimalField` class. Although they both represent real numbers, they
  567. represent those numbers differently. ``FloatField`` uses Python's ``float``
  568. type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
  569. information on the difference between the two, see Python's documentation
  570. for the :mod:`decimal` module.
  571. ``ImageField``
  572. --------------
  573. .. class:: ImageField([upload_to=None, height_field=None, width_field=None, max_length=100, **options])
  574. Inherits all attributes and methods from :class:`FileField`, but also
  575. validates that the uploaded object is a valid image.
  576. In addition to the special attributes that are available for :class:`FileField`,
  577. an :class:`ImageField` also has ``height`` and ``width`` attributes.
  578. To facilitate querying on those attributes, :class:`ImageField` has two extra
  579. optional arguments:
  580. .. attribute:: ImageField.height_field
  581. Name of a model field which will be auto-populated with the height of the
  582. image each time the model instance is saved.
  583. .. attribute:: ImageField.width_field
  584. Name of a model field which will be auto-populated with the width of the
  585. image each time the model instance is saved.
  586. Requires the `Pillow`_ library.
  587. .. _Pillow: http://python-imaging.github.io/Pillow/
  588. By default, :class:`ImageField` instances are created as ``varchar(100)``
  589. columns in your database. As with other fields, you can change the maximum
  590. length using the :attr:`~CharField.max_length` argument.
  591. The default form widget for this field is a
  592. :class:`~django.forms.ClearableFileInput`.
  593. ``IntegerField``
  594. ----------------
  595. .. class:: IntegerField([**options])
  596. An integer. Values from ``-2147483648`` to ``2147483647`` are safe in all
  597. databases supported by Django. The default form widget for this field is a
  598. :class:`~django.forms.TextInput`.
  599. ``IPAddressField``
  600. ------------------
  601. .. class:: IPAddressField([**options])
  602. .. deprecated:: 1.7
  603. This field has been deprecated in favor of
  604. :class:`~django.db.models.GenericIPAddressField`.
  605. An IP address, in string format (e.g. "192.0.2.30"). The default form widget
  606. for this field is a :class:`~django.forms.TextInput`.
  607. ``GenericIPAddressField``
  608. -------------------------
  609. .. class:: GenericIPAddressField([protocol=both, unpack_ipv4=False, **options])
  610. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
  611. ``2a02:42fe::4``). The default form widget for this field is a
  612. :class:`~django.forms.TextInput`.
  613. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  614. including using the IPv4 format suggested in paragraph 3 of that section, like
  615. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  616. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  617. are converted to lowercase.
  618. .. attribute:: GenericIPAddressField.protocol
  619. Limits valid inputs to the specified protocol.
  620. Accepted values are ``'both'`` (default), ``'IPv4'``
  621. or ``'IPv6'``. Matching is case insensitive.
  622. .. attribute:: GenericIPAddressField.unpack_ipv4
  623. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  624. If this option is enabled that address would be unpacked to
  625. ``192.0.2.1``. Default is disabled. Can only be used
  626. when ``protocol`` is set to ``'both'``.
  627. If you allow for blank values, you have to allow for null values since blank
  628. values are stored as null.
  629. ``NullBooleanField``
  630. --------------------
  631. .. class:: NullBooleanField([**options])
  632. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  633. this instead of a :class:`BooleanField` with ``null=True``. The default form
  634. widget for this field is a :class:`~django.forms.NullBooleanSelect`.
  635. ``PositiveIntegerField``
  636. ------------------------
  637. .. class:: PositiveIntegerField([**options])
  638. Like an :class:`IntegerField`, but must be either positive or zero (``0``).
  639. Values from ``0`` to ``2147483647`` are safe in all databases supported by
  640. Django. The value ``0`` is accepted for backward compatibility reasons.
  641. ``PositiveSmallIntegerField``
  642. -----------------------------
  643. .. class:: PositiveSmallIntegerField([**options])
  644. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  645. (database-dependent) point. Values from ``0`` to ``32767`` are safe in all
  646. databases supported by Django.
  647. ``SlugField``
  648. -------------
  649. .. class:: SlugField([max_length=50, **options])
  650. :term:`Slug` is a newspaper term. A slug is a short label for something,
  651. containing only letters, numbers, underscores or hyphens. They're generally used
  652. in URLs.
  653. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  654. about database portability and :attr:`~CharField.max_length` in that section,
  655. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  656. default length of 50.
  657. Implies setting :attr:`Field.db_index` to ``True``.
  658. It is often useful to automatically prepopulate a SlugField based on the value
  659. of some other value. You can do this automatically in the admin using
  660. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  661. ``SmallIntegerField``
  662. ---------------------
  663. .. class:: SmallIntegerField([**options])
  664. Like an :class:`IntegerField`, but only allows values under a certain
  665. (database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all
  666. databases supported by Django.
  667. ``TextField``
  668. -------------
  669. .. class:: TextField([**options])
  670. A large text field. The default form widget for this field is a
  671. :class:`~django.forms.Textarea`.
  672. .. versionchanged:: 1.7
  673. If you specify a ``max_length`` attribute, it will be reflected in the
  674. :class:`~django.forms.Textarea` widget of the auto-generated form field.
  675. However it is not enforced at the model or database level. Use a
  676. :class:`CharField` for that.
  677. .. admonition:: MySQL users
  678. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  679. collation (which is *not* the default), there are some issues to be aware
  680. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  681. details.
  682. ``TimeField``
  683. -------------
  684. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  685. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  686. auto-population options as :class:`DateField`.
  687. The default form widget for this field is a :class:`~django.forms.TextInput`.
  688. The admin adds some JavaScript shortcuts.
  689. ``URLField``
  690. ------------
  691. .. class:: URLField([max_length=200, **options])
  692. A :class:`CharField` for a URL.
  693. The default form widget for this field is a :class:`~django.forms.TextInput`.
  694. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  695. :attr:`~CharField.max_length` argument. If you don't specify
  696. :attr:`~CharField.max_length`, a default of 200 is used.
  697. Relationship fields
  698. ===================
  699. .. module:: django.db.models.fields.related
  700. :synopsis: Related field types
  701. .. currentmodule:: django.db.models
  702. Django also defines a set of fields that represent relations.
  703. .. _ref-foreignkey:
  704. ``ForeignKey``
  705. --------------
  706. .. class:: ForeignKey(othermodel, [**options])
  707. A many-to-one relationship. Requires a positional argument: the class to which
  708. the model is related.
  709. .. _recursive-relationships:
  710. To create a recursive relationship -- an object that has a many-to-one
  711. relationship with itself -- use ``models.ForeignKey('self')``.
  712. .. _lazy-relationships:
  713. If you need to create a relationship on a model that has not yet been defined,
  714. you can use the name of the model, rather than the model object itself::
  715. from django.db import models
  716. class Car(models.Model):
  717. manufacturer = models.ForeignKey('Manufacturer')
  718. # ...
  719. class Manufacturer(models.Model):
  720. # ...
  721. pass
  722. To refer to models defined in another application, you can explicitly specify
  723. a model with the full application label. For example, if the ``Manufacturer``
  724. model above is defined in another application called ``production``, you'd
  725. need to use::
  726. class Car(models.Model):
  727. manufacturer = models.ForeignKey('production.Manufacturer')
  728. This sort of reference can be useful when resolving circular import
  729. dependencies between two applications.
  730. A database index is automatically created on the ``ForeignKey``. You can
  731. disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
  732. avoid the overhead of an index if you are creating a foreign key for
  733. consistency rather than joins, or if you will be creating an alternative index
  734. like a partial or multiple column index.
  735. Database Representation
  736. ~~~~~~~~~~~~~~~~~~~~~~~
  737. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  738. database column name. In the above example, the database table for the ``Car``
  739. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  740. specifying :attr:`~Field.db_column`) However, your code should never have to
  741. deal with the database column name, unless you write custom SQL. You'll always
  742. deal with the field names of your model object.
  743. .. _foreign-key-arguments:
  744. Arguments
  745. ~~~~~~~~~
  746. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  747. define the details of how the relation works.
  748. .. attribute:: ForeignKey.limit_choices_to
  749. Sets a limit to the available choices for this field when this field is
  750. rendered using a ``ModelForm`` or the admin (by default, all objects
  751. in the queryset are available to choose). Either a dictionary, a
  752. :class:`~django.db.models.Q` object, or a callable returning a
  753. dictionary or :class:`~django.db.models.Q` object can be used.
  754. For example::
  755. staff_member = models.ForeignKey(User, limit_choices_to={'is_staff': True})
  756. causes the corresponding field on the ``ModelForm`` to list only ``Users``
  757. that have ``is_staff=True``. This may be helpful in the Django admin.
  758. The callable form can be helpful, for instance, when used in conjunction
  759. with the Python ``datetime`` module to limit selections by date range. For
  760. example::
  761. limit_choices_to = lambda: {'pub_date__lte': datetime.date.utcnow()}
  762. If ``limit_choices_to`` is or returns a :class:`Q object
  763. <django.db.models.Q>`, which is useful for :ref:`complex queries
  764. <complex-lookups-with-q>`, then it will only have an effect on the choices
  765. available in the admin when the field is not listed in
  766. :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the
  767. ``ModelAdmin`` for the model.
  768. .. versionchanged:: 1.7
  769. Previous versions of Django do not allow passing a callable as a value
  770. for ``limit_choices_to``.
  771. .. note::
  772. If a callable is used for ``limit_choices_to``, it will be invoked
  773. every time a new form is instantiated. It may also be invoked when a
  774. model is validated, for example by management commands or the admin.
  775. The admin constructs querysets to validate its form inputs in various
  776. edge cases multiple times, so there is a possibility your callable may
  777. be invoked several times.
  778. .. attribute:: ForeignKey.related_name
  779. The name to use for the relation from the related object back to this one.
  780. It's also the default value for :attr:`related_query_name` (the name to use
  781. for the reverse filter name from the target model). See the :ref:`related
  782. objects documentation <backwards-related-objects>` for a full explanation
  783. and example. Note that you must set this value when defining relations on
  784. :ref:`abstract models <abstract-base-classes>`; and when you do so
  785. :ref:`some special syntax <abstract-related-name>` is available.
  786. If you'd prefer Django not to create a backwards relation, set
  787. ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
  788. ensure that the ``User`` model won't have a backwards relation to this
  789. model::
  790. user = models.ForeignKey(User, related_name='+')
  791. .. attribute:: ForeignKey.related_query_name
  792. .. versionadded:: 1.6
  793. The name to use for the reverse filter name from the target model.
  794. Defaults to the value of :attr:`related_name` if it is set, otherwise it
  795. defaults to the name of the model::
  796. # Declare the ForeignKey with related_query_name
  797. class Tag(models.Model):
  798. article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
  799. name = models.CharField(max_length=255)
  800. # That's now the name of the reverse filter
  801. article_instance.filter(tag__name="important")
  802. .. attribute:: ForeignKey.to_field
  803. The field on the related object that the relation is to. By default, Django
  804. uses the primary key of the related object.
  805. .. attribute:: ForeignKey.db_constraint
  806. .. versionadded:: 1.6
  807. Controls whether or not a constraint should be created in the database for
  808. this foreign key. The default is ``True``, and that's almost certainly what
  809. you want; setting this to ``False`` can be very bad for data integrity.
  810. That said, here are some scenarios where you might want to do this:
  811. * You have legacy data that is not valid.
  812. * You're sharding your database.
  813. If this is set to ``False``, accessing a related object that doesn't exist
  814. will raise its ``DoesNotExist`` exception.
  815. .. attribute:: ForeignKey.on_delete
  816. When an object referenced by a :class:`ForeignKey` is deleted, Django by
  817. default emulates the behavior of the SQL constraint ``ON DELETE CASCADE``
  818. and also deletes the object containing the ``ForeignKey``. This behavior
  819. can be overridden by specifying the :attr:`on_delete` argument. For
  820. example, if you have a nullable :class:`ForeignKey` and you want it to be
  821. set null when the referenced object is deleted::
  822. user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
  823. The possible values for :attr:`~ForeignKey.on_delete` are found in
  824. :mod:`django.db.models`:
  825. * .. attribute:: CASCADE
  826. Cascade deletes; the default.
  827. * .. attribute:: PROTECT
  828. Prevent deletion of the referenced object by raising
  829. :exc:`~django.db.models.ProtectedError`, a subclass of
  830. :exc:`django.db.IntegrityError`.
  831. * .. attribute:: SET_NULL
  832. Set the :class:`ForeignKey` null; this is only possible if
  833. :attr:`~Field.null` is ``True``.
  834. * .. attribute:: SET_DEFAULT
  835. Set the :class:`ForeignKey` to its default value; a default for the
  836. :class:`ForeignKey` must be set.
  837. * .. function:: SET()
  838. Set the :class:`ForeignKey` to the value passed to
  839. :func:`~django.db.models.SET()`, or if a callable is passed in,
  840. the result of calling it. In most cases, passing a callable will be
  841. necessary to avoid executing queries at the time your models.py is
  842. imported::
  843. from django.db import models
  844. from django.contrib.auth.models import User
  845. def get_sentinel_user():
  846. return User.objects.get_or_create(username='deleted')[0]
  847. class MyModel(models.Model):
  848. user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
  849. * .. attribute:: DO_NOTHING
  850. Take no action. If your database backend enforces referential
  851. integrity, this will cause an :exc:`~django.db.IntegrityError` unless
  852. you manually add an SQL ``ON DELETE`` constraint to the database field
  853. (perhaps using :ref:`initial sql<initial-sql>`).
  854. .. attribute:: ForeignKey.swappable
  855. .. versionadded:: 1.7
  856. Controls the migration framework's reaction if this :class:`ForeignKey`
  857. is pointing at a swappable model. If it is ``True`` - the default -
  858. then if the :class:`ForeignKey` is pointing at a model which matches
  859. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  860. model setting) the relationship will be stored in the migration using
  861. a reference to the setting, not to the model directly.
  862. You only want to override this to be ``False`` if you are sure your
  863. model should always point towards the swapped-in model - for example,
  864. if it is a profile model designed specifically for your custom user model.
  865. If in doubt, leave it to its default of ``True``.
  866. .. _ref-manytomany:
  867. ``ManyToManyField``
  868. -------------------
  869. .. class:: ManyToManyField(othermodel, [**options])
  870. A many-to-many relationship. Requires a positional argument: the class to
  871. which the model is related, which works exactly the same as it does for
  872. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
  873. :ref:`lazy <lazy-relationships>` relationships.
  874. Related objects can be added, removed, or created with the field's
  875. :class:`~django.db.models.fields.related.RelatedManager`.
  876. Database Representation
  877. ~~~~~~~~~~~~~~~~~~~~~~~
  878. Behind the scenes, Django creates an intermediary join table to represent the
  879. many-to-many relationship. By default, this table name is generated using the
  880. name of the many-to-many field and the name of the table for the model that
  881. contains it. Since some databases don't support table names above a certain
  882. length, these table names will be automatically truncated to 64 characters and a
  883. uniqueness hash will be used. This means you might see table names like
  884. ``author_books_9cdf4``; this is perfectly normal. You can manually provide the
  885. name of the join table using the :attr:`~ManyToManyField.db_table` option.
  886. .. _manytomany-arguments:
  887. Arguments
  888. ~~~~~~~~~
  889. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  890. that control how the relationship functions.
  891. .. attribute:: ManyToManyField.related_name
  892. Same as :attr:`ForeignKey.related_name`.
  893. .. attribute:: ManyToManyField.related_query_name
  894. .. versionadded:: 1.6
  895. Same as :attr:`ForeignKey.related_query_name`.
  896. .. attribute:: ManyToManyField.limit_choices_to
  897. Same as :attr:`ForeignKey.limit_choices_to`.
  898. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  899. custom intermediate table specified using the
  900. :attr:`~ManyToManyField.through` parameter.
  901. .. attribute:: ManyToManyField.symmetrical
  902. Only used in the definition of ManyToManyFields on self. Consider the
  903. following model::
  904. from django.db import models
  905. class Person(models.Model):
  906. friends = models.ManyToManyField("self")
  907. When Django processes this model, it identifies that it has a
  908. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  909. ``person_set`` attribute to the ``Person`` class. Instead, the
  910. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  911. your friend, then you are my friend.
  912. If you do not want symmetry in many-to-many relationships with ``self``, set
  913. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  914. add the descriptor for the reverse relationship, allowing
  915. :class:`ManyToManyField` relationships to be non-symmetrical.
  916. .. attribute:: ManyToManyField.through
  917. Django will automatically generate a table to manage many-to-many
  918. relationships. However, if you want to manually specify the intermediary
  919. table, you can use the :attr:`~ManyToManyField.through` option to specify
  920. the Django model that represents the intermediate table that you want to
  921. use.
  922. The most common use for this option is when you want to associate
  923. :ref:`extra data with a many-to-many relationship
  924. <intermediary-manytomany>`.
  925. .. attribute:: ManyToManyField.through_fields
  926. .. versionadded:: 1.7
  927. Only used when a custom intermediary model is specified. Django will
  928. normally determine which fields of the intermediary model to use in order
  929. to establish a many-to-many relationship automatically. However,
  930. consider the following models::
  931. from django.db import models
  932. class Person(models.Model):
  933. name = models.CharField(max_length=50)
  934. class Group(models.Model):
  935. name = models.CharField(max_length=128)
  936. members = models.ManyToManyField(Person, through='Membership', through_fields=('group', 'person'))
  937. class Membership(models.Model):
  938. group = models.ForeignKey(Group)
  939. person = models.ForeignKey(Person)
  940. inviter = models.ForeignKey(Person, related_name="membership_invites")
  941. invite_reason = models.CharField(max_length=64)
  942. ``Membership`` has *two* foreign keys to ``Person`` (``person`` and
  943. ``inviter``), which makes the relationship ambiguous and Django can't know
  944. which one to use. In this case, you must explicitly specify which
  945. foreign keys Django should use using ``through_fields``, as in the example
  946. above.
  947. ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where
  948. ``field1`` is the name of the foreign key to the model the
  949. :class:`ManyToManyField` is defined on (``group`` in this case), and
  950. ``field2`` the name of the foreign key to the target model (``person``
  951. in this case).
  952. When you have more than one foreign key on an intermediary model to any
  953. (or even both) of the models participating in a many-to-many relationship,
  954. you *must* specify ``through_fields``. This also applies to
  955. :ref:`recursive relationships <recursive-relationships>`
  956. when an intermediary model is used and there are more than two
  957. foreign keys to the model, or you want to explicitly specify which two
  958. Django should use.
  959. Recursive relationships using an intermediary model are always defined as
  960. non-symmetrical -- that is, with :attr:`symmetrical=False <ManyToManyField.symmetrical>`
  961. -- therefore, there is the concept of a "source" and a "target". In that
  962. case ``'field1'`` will be treated as the "source" of the relationship and
  963. ``'field2'`` as the "target".
  964. .. attribute:: ManyToManyField.db_table
  965. The name of the table to create for storing the many-to-many data. If this
  966. is not provided, Django will assume a default name based upon the names of:
  967. the table for the model defining the relationship and the name of the field
  968. itself.
  969. .. attribute:: ManyToManyField.db_constraint
  970. .. versionadded:: 1.6
  971. Controls whether or not constraints should be created in the database for
  972. the foreign keys in the intermediary table. The default is ``True``, and
  973. that's almost certainly what you want; setting this to ``False`` can be
  974. very bad for data integrity. That said, here are some scenarios where you
  975. might want to do this:
  976. * You have legacy data that is not valid.
  977. * You're sharding your database.
  978. It is an error to pass both ``db_constraint`` and ``through``.
  979. .. attribute:: ManyToManyField.swappable
  980. .. versionadded:: 1.7
  981. Controls the migration framework's reaction if this :class:`ManyToManyField`
  982. is pointing at a swappable model. If it is ``True`` - the default -
  983. then if the :class:`ManyToManyField` is pointing at a model which matches
  984. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  985. model setting) the relationship will be stored in the migration using
  986. a reference to the setting, not to the model directly.
  987. You only want to override this to be ``False`` if you are sure your
  988. model should always point towards the swapped-in model - for example,
  989. if it is a profile model designed specifically for your custom user model.
  990. If in doubt, leave it to its default of ``True``.
  991. .. _ref-onetoone:
  992. ``OneToOneField``
  993. -----------------
  994. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  995. A one-to-one relationship. Conceptually, this is similar to a
  996. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  997. "reverse" side of the relation will directly return a single object.
  998. This is most useful as the primary key of a model which "extends"
  999. another model in some way; :ref:`multi-table-inheritance` is
  1000. implemented by adding an implicit one-to-one relation from the child
  1001. model to the parent model, for example.
  1002. One positional argument is required: the class to which the model will be
  1003. related. This works exactly the same as it does for :class:`ForeignKey`,
  1004. including all the options regarding :ref:`recursive <recursive-relationships>`
  1005. and :ref:`lazy <lazy-relationships>` relationships.
  1006. If you do not specify the :attr:`~ForeignKey.related_name` argument for
  1007. the ``OneToOneField``, Django will use the lower-case name of the current model
  1008. as default value.
  1009. With the following example::
  1010. from django.db import models
  1011. from django.contrib.auth.models import User
  1012. class MySpecialUser(models.Model):
  1013. user = models.OneToOneField(User)
  1014. supervisor = models.OneToOneField(User, related_name='supervisor_of')
  1015. your resulting ``User`` model will have the following attributes::
  1016. >>> user = User.objects.get(pk=1)
  1017. >>> hasattr(user, 'myspecialuser')
  1018. True
  1019. >>> hasattr(user, 'supervisor_of')
  1020. True
  1021. .. _onetoone-arguments:
  1022. Additionally, ``OneToOneField`` accepts all of the extra arguments
  1023. accepted by :class:`ForeignKey`, plus one extra argument:
  1024. .. attribute:: OneToOneField.parent_link
  1025. When ``True`` and used in a model which inherits from another
  1026. (concrete) model, indicates that this field should be used as the
  1027. link back to the parent class, rather than the extra
  1028. ``OneToOneField`` which would normally be implicitly created by
  1029. subclassing.
  1030. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
  1031. examples of ``OneToOneField``.