fields.txt 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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. A field to store raw binary data. It only supports ``bytes`` assignment. Be
  275. aware that this field has limited functionality. For example, it is not possible
  276. to filter a queryset on a ``BinaryField`` value.
  277. .. admonition:: Abusing ``BinaryField``
  278. Although you might think about storing files in the database, consider that
  279. it is bad design in 99% of the cases. This field is *not* a replacement for
  280. proper :doc:`static files </howto/static-files/index>` handling.
  281. ``BooleanField``
  282. ----------------
  283. .. class:: BooleanField(**options)
  284. A true/false field.
  285. The default form widget for this field is a
  286. :class:`~django.forms.CheckboxInput`.
  287. If you need to accept :attr:`~Field.null` values then use
  288. :class:`NullBooleanField` instead.
  289. The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
  290. isn't defined.
  291. ``CharField``
  292. -------------
  293. .. class:: CharField(max_length=None, [**options])
  294. A string field, for small- to large-sized strings.
  295. For large amounts of text, use :class:`~django.db.models.TextField`.
  296. The default form widget for this field is a :class:`~django.forms.TextInput`.
  297. :class:`CharField` has one extra required argument:
  298. .. attribute:: CharField.max_length
  299. The maximum length (in characters) of the field. The max_length is enforced
  300. at the database level and in Django's validation.
  301. .. note::
  302. If you are writing an application that must be portable to multiple
  303. database backends, you should be aware that there are restrictions on
  304. ``max_length`` for some backends. Refer to the :doc:`database backend
  305. notes </ref/databases>` for details.
  306. .. admonition:: MySQL users
  307. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  308. collation (which is *not* the default), there are some issues to be aware
  309. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  310. details.
  311. ``CommaSeparatedIntegerField``
  312. ------------------------------
  313. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  314. A field of integers separated by commas. As in :class:`CharField`, the
  315. :attr:`~CharField.max_length` argument is required and the note about database
  316. portability mentioned there should be heeded.
  317. ``DateField``
  318. -------------
  319. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  320. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  321. optional arguments:
  322. .. attribute:: DateField.auto_now
  323. Automatically set the field to now every time the object is saved. Useful
  324. for "last-modified" timestamps. Note that the current date is *always*
  325. used; it's not just a default value that you can override.
  326. .. attribute:: DateField.auto_now_add
  327. Automatically set the field to now when the object is first created. Useful
  328. for creation of timestamps. Note that the current date is *always* used;
  329. it's not just a default value that you can override.
  330. The default form widget for this field is a
  331. :class:`~django.forms.TextInput`. The admin adds a JavaScript calendar,
  332. and a shortcut for "Today". Includes an additional ``invalid_date`` error
  333. message key.
  334. .. note::
  335. As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
  336. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  337. set.
  338. ``DateTimeField``
  339. -----------------
  340. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  341. A date and time, represented in Python by a ``datetime.datetime`` instance.
  342. Takes the same extra arguments as :class:`DateField`.
  343. The default form widget for this field is a single
  344. :class:`~django.forms.TextInput`. The admin uses two separate
  345. :class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
  346. ``DecimalField``
  347. ----------------
  348. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  349. A fixed-precision decimal number, represented in Python by a
  350. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  351. .. attribute:: DecimalField.max_digits
  352. The maximum number of digits allowed in the number. Note that this number
  353. must be greater than or equal to ``decimal_places``.
  354. .. attribute:: DecimalField.decimal_places
  355. The number of decimal places to store with the number.
  356. For example, to store numbers up to ``999`` with a resolution of 2 decimal
  357. places, you'd use::
  358. models.DecimalField(..., max_digits=5, decimal_places=2)
  359. And to store numbers up to approximately one billion with a resolution of 10
  360. decimal places::
  361. models.DecimalField(..., max_digits=19, decimal_places=10)
  362. The default form widget for this field is a :class:`~django.forms.TextInput`.
  363. .. note::
  364. For more information about the differences between the
  365. :class:`FloatField` and :class:`DecimalField` classes, please
  366. see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`.
  367. ``EmailField``
  368. --------------
  369. .. class:: EmailField([max_length=75, **options])
  370. A :class:`CharField` that checks that the value is a valid email address.
  371. .. admonition:: Incompliance to RFCs
  372. The default 75 character ``max_length`` is not capable of storing all
  373. possible RFC3696/5321-compliant email addresses. In order to store all
  374. possible valid email addresses, a ``max_length`` of 254 is required.
  375. The default ``max_length`` of 75 exists for historical reasons. The
  376. default has not been changed in order to maintain backwards
  377. compatibility with existing uses of :class:`EmailField`.
  378. ``FileField``
  379. -------------
  380. .. class:: FileField([upload_to=None, max_length=100, **options])
  381. A file-upload field.
  382. .. note::
  383. The ``primary_key`` and ``unique`` arguments are not supported, and will
  384. raise a ``TypeError`` if used.
  385. Has two optional arguments:
  386. .. attribute:: FileField.upload_to
  387. .. versionchanged:: 1.7
  388. ``upload_to`` was required in older versions of Django.
  389. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  390. setting to determine the value of the
  391. :attr:`~django.db.models.fields.files.FieldFile.url` attribute.
  392. This path may contain :func:`~time.strftime` formatting, which will be
  393. replaced by the date/time of the file upload (so that uploaded files don't
  394. fill up the given directory).
  395. This may also be a callable, such as a function, which will be called to
  396. obtain the upload path, including the filename. This callable must be able
  397. to accept two arguments, and return a Unix-style path (with forward slashes)
  398. to be passed along to the storage system. The two arguments that will be
  399. passed are:
  400. ====================== ===============================================
  401. Argument Description
  402. ====================== ===============================================
  403. ``instance`` An instance of the model where the
  404. ``FileField`` is defined. More specifically,
  405. this is the particular instance where the
  406. current file is being attached.
  407. In most cases, this object will not have been
  408. saved to the database yet, so if it uses the
  409. default ``AutoField``, *it might not yet have a
  410. value for its primary key field*.
  411. ``filename`` The filename that was originally given to the
  412. file. This may or may not be taken into account
  413. when determining the final destination path.
  414. ====================== ===============================================
  415. .. attribute:: FileField.storage
  416. A storage object, which handles the storage and retrieval of your
  417. files. See :doc:`/topics/files` for details on how to provide this object.
  418. The default form widget for this field is a
  419. :class:`~django.forms.ClearableFileInput`.
  420. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  421. takes a few steps:
  422. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  423. full path to a directory where you'd like Django to store uploaded files.
  424. (For performance, these files are not stored in the database.) Define
  425. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  426. that this directory is writable by the Web server's user account.
  427. 2. Add the :class:`FileField` or :class:`ImageField` to your model, defining
  428. the :attr:`~FileField.upload_to` option to specify a subdirectory of
  429. :setting:`MEDIA_ROOT` to use for uploaded files.
  430. 3. All that will be stored in your database is a path to the file
  431. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  432. convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
  433. provided by Django. For example, if your :class:`ImageField` is called
  434. ``mug_shot``, you can get the absolute path to your image in a template with
  435. ``{{ object.mug_shot.url }}``.
  436. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  437. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  438. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
  439. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
  440. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
  441. the directory ``/home/media/photos/2007/01/15``.
  442. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
  443. size, you could use the :attr:`~django.core.files.File.name` and
  444. :attr:`~django.core.files.File.size` attributes respectively; for more
  445. information on the available attributes and methods, see the
  446. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
  447. topic guide.
  448. .. note::
  449. The file is saved as part of saving the model in the database, so the actual
  450. file name used on disk cannot be relied on until after the model has been
  451. saved.
  452. The uploaded file's relative URL can be obtained using the
  453. :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
  454. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
  455. underlying :class:`~django.core.files.storage.Storage` class.
  456. .. _file-upload-security:
  457. Note that whenever you deal with uploaded files, you should pay close attention
  458. to where you're uploading them and what type of files they are, to avoid
  459. security holes. *Validate all uploaded files* so that you're sure the files are
  460. what you think they are. For example, if you blindly let somebody upload files,
  461. without validation, to a directory that's within your Web server's document
  462. root, then somebody could upload a CGI or PHP script and execute that script by
  463. visiting its URL on your site. Don't allow that.
  464. Also note that even an uploaded HTML file, since it can be executed by the
  465. browser (though not by the server), can pose security threats that are
  466. equivalent to XSS or CSRF attacks.
  467. By default, :class:`FileField` instances are
  468. created as ``varchar(100)`` columns in your database. As with other fields, you
  469. can change the maximum length using the :attr:`~CharField.max_length` argument.
  470. FileField and FieldFile
  471. ~~~~~~~~~~~~~~~~~~~~~~~
  472. .. currentmodule:: django.db.models.fields.files
  473. .. class:: FieldFile
  474. When you access a :class:`~django.db.models.FileField` on a model, you are
  475. given an instance of :class:`FieldFile` as a proxy for accessing the underlying
  476. file. This class has several attributes and methods that can be used to
  477. interact with file data:
  478. .. attribute:: FieldFile.url
  479. A read-only property to access the file's relative URL by calling the
  480. :meth:`~django.core.files.storage.Storage.url` method of the underlying
  481. :class:`~django.core.files.storage.Storage` class.
  482. .. method:: FieldFile.open(mode='rb')
  483. Behaves like the standard Python ``open()`` method and opens the file
  484. associated with this instance in the mode specified by ``mode``.
  485. .. method:: FieldFile.close()
  486. Behaves like the standard Python ``file.close()`` method and closes the file
  487. associated with this instance.
  488. .. method:: FieldFile.save(name, content, save=True)
  489. This method takes a filename and file contents and passes them to the storage
  490. class for the field, then associates the stored file with the model field.
  491. If you want to manually associate file data with
  492. :class:`~django.db.models.FileField` instances on your model, the ``save()``
  493. method is used to persist that file data.
  494. Takes two required arguments: ``name`` which is the name of the file, and
  495. ``content`` which is an object containing the file's contents. The
  496. optional ``save`` argument controls whether or not the instance is
  497. saved after the file has been altered. Defaults to ``True``.
  498. Note that the ``content`` argument should be an instance of
  499. :class:`django.core.files.File`, not Python's built-in file object.
  500. You can construct a :class:`~django.core.files.File` from an existing
  501. Python file object like this::
  502. from django.core.files import File
  503. # Open an existing file using Python's built-in open()
  504. f = open('/tmp/hello.world')
  505. myfile = File(f)
  506. Or you can construct one from a Python string like this::
  507. from django.core.files.base import ContentFile
  508. myfile = ContentFile("hello world")
  509. For more information, see :doc:`/topics/files`.
  510. .. method:: FieldFile.delete(save=True)
  511. Deletes the file associated with this instance and clears all attributes on
  512. the field. Note: This method will close the file if it happens to be open when
  513. ``delete()`` is called.
  514. The optional ``save`` argument controls whether or not the instance is saved
  515. after the file has been deleted. Defaults to ``True``.
  516. Note that when a model is deleted, related files are not deleted. If you need
  517. to cleanup orphaned files, you'll need to handle it yourself (for instance,
  518. with a custom management command that can be run manually or scheduled to run
  519. periodically via e.g. cron).
  520. .. currentmodule:: django.db.models
  521. ``FilePathField``
  522. -----------------
  523. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  524. A :class:`CharField` whose choices are limited to the filenames in a certain
  525. directory on the filesystem. Has three special arguments, of which the first is
  526. **required**:
  527. .. attribute:: FilePathField.path
  528. Required. The absolute filesystem path to a directory from which this
  529. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  530. .. attribute:: FilePathField.match
  531. Optional. A regular expression, as a string, that :class:`FilePathField`
  532. will use to filter filenames. Note that the regex will be applied to the
  533. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  534. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
  535. .. attribute:: FilePathField.recursive
  536. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  537. whether all subdirectories of :attr:`~FilePathField.path` should be included
  538. .. attribute:: FilePathField.allow_files
  539. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  540. whether files in the specified location should be included. Either this or
  541. :attr:`~FilePathField.allow_folders` must be ``True``.
  542. .. attribute:: FilePathField.allow_folders
  543. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  544. whether folders in the specified location should be included. Either this
  545. or :attr:`~FilePathField.allow_files` must be ``True``.
  546. Of course, these arguments can be used together.
  547. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  548. base filename, not the full path. So, this example::
  549. FilePathField(path="/home/images", match="foo.*", recursive=True)
  550. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
  551. because the :attr:`~FilePathField.match` applies to the base filename
  552. (``foo.png`` and ``bar.png``).
  553. By default, :class:`FilePathField` instances are
  554. created as ``varchar(100)`` columns in your database. As with other fields, you
  555. can change the maximum length using the :attr:`~CharField.max_length` argument.
  556. ``FloatField``
  557. --------------
  558. .. class:: FloatField([**options])
  559. A floating-point number represented in Python by a ``float`` instance.
  560. The default form widget for this field is a :class:`~django.forms.TextInput`.
  561. .. _floatfield_vs_decimalfield:
  562. .. admonition:: ``FloatField`` vs. ``DecimalField``
  563. The :class:`FloatField` class is sometimes mixed up with the
  564. :class:`DecimalField` class. Although they both represent real numbers, they
  565. represent those numbers differently. ``FloatField`` uses Python's ``float``
  566. type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
  567. information on the difference between the two, see Python's documentation
  568. for the :mod:`decimal` module.
  569. ``ImageField``
  570. --------------
  571. .. class:: ImageField([upload_to=None, height_field=None, width_field=None, max_length=100, **options])
  572. Inherits all attributes and methods from :class:`FileField`, but also
  573. validates that the uploaded object is a valid image.
  574. In addition to the special attributes that are available for :class:`FileField`,
  575. an :class:`ImageField` also has ``height`` and ``width`` attributes.
  576. To facilitate querying on those attributes, :class:`ImageField` has two extra
  577. optional arguments:
  578. .. attribute:: ImageField.height_field
  579. Name of a model field which will be auto-populated with the height of the
  580. image each time the model instance is saved.
  581. .. attribute:: ImageField.width_field
  582. Name of a model field which will be auto-populated with the width of the
  583. image each time the model instance is saved.
  584. Requires the `Pillow`_ library.
  585. .. _Pillow: http://python-imaging.github.io/Pillow/
  586. By default, :class:`ImageField` instances are created as ``varchar(100)``
  587. columns in your database. As with other fields, you can change the maximum
  588. length using the :attr:`~CharField.max_length` argument.
  589. The default form widget for this field is a
  590. :class:`~django.forms.ClearableFileInput`.
  591. ``IntegerField``
  592. ----------------
  593. .. class:: IntegerField([**options])
  594. An integer. Values from ``-2147483648`` to ``2147483647`` are safe in all
  595. databases supported by Django. The default form widget for this field is a
  596. :class:`~django.forms.TextInput`.
  597. ``IPAddressField``
  598. ------------------
  599. .. class:: IPAddressField([**options])
  600. .. deprecated:: 1.7
  601. This field has been deprecated in favor of
  602. :class:`~django.db.models.GenericIPAddressField`.
  603. An IP address, in string format (e.g. "192.0.2.30"). The default form widget
  604. for this field is a :class:`~django.forms.TextInput`.
  605. ``GenericIPAddressField``
  606. -------------------------
  607. .. class:: GenericIPAddressField([protocol=both, unpack_ipv4=False, **options])
  608. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
  609. ``2a02:42fe::4``). The default form widget for this field is a
  610. :class:`~django.forms.TextInput`.
  611. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  612. including using the IPv4 format suggested in paragraph 3 of that section, like
  613. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  614. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  615. are converted to lowercase.
  616. .. attribute:: GenericIPAddressField.protocol
  617. Limits valid inputs to the specified protocol.
  618. Accepted values are ``'both'`` (default), ``'IPv4'``
  619. or ``'IPv6'``. Matching is case insensitive.
  620. .. attribute:: GenericIPAddressField.unpack_ipv4
  621. Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.
  622. If this option is enabled that address would be unpacked to
  623. ``192.0.2.1``. Default is disabled. Can only be used
  624. when ``protocol`` is set to ``'both'``.
  625. If you allow for blank values, you have to allow for null values since blank
  626. values are stored as null.
  627. ``NullBooleanField``
  628. --------------------
  629. .. class:: NullBooleanField([**options])
  630. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  631. this instead of a :class:`BooleanField` with ``null=True``. The default form
  632. widget for this field is a :class:`~django.forms.NullBooleanSelect`.
  633. ``PositiveIntegerField``
  634. ------------------------
  635. .. class:: PositiveIntegerField([**options])
  636. Like an :class:`IntegerField`, but must be either positive or zero (``0``).
  637. Values from ``0`` to ``2147483647`` are safe in all databases supported by
  638. Django. The value ``0`` is accepted for backward compatibility reasons.
  639. ``PositiveSmallIntegerField``
  640. -----------------------------
  641. .. class:: PositiveSmallIntegerField([**options])
  642. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  643. (database-dependent) point. Values from ``0`` to ``32767`` are safe in all
  644. databases supported by Django.
  645. ``SlugField``
  646. -------------
  647. .. class:: SlugField([max_length=50, **options])
  648. :term:`Slug` is a newspaper term. A slug is a short label for something,
  649. containing only letters, numbers, underscores or hyphens. They're generally used
  650. in URLs.
  651. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  652. about database portability and :attr:`~CharField.max_length` in that section,
  653. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  654. default length of 50.
  655. Implies setting :attr:`Field.db_index` to ``True``.
  656. It is often useful to automatically prepopulate a SlugField based on the value
  657. of some other value. You can do this automatically in the admin using
  658. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  659. ``SmallIntegerField``
  660. ---------------------
  661. .. class:: SmallIntegerField([**options])
  662. Like an :class:`IntegerField`, but only allows values under a certain
  663. (database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all
  664. databases supported by Django.
  665. ``TextField``
  666. -------------
  667. .. class:: TextField([**options])
  668. A large text field. The default form widget for this field is a
  669. :class:`~django.forms.Textarea`.
  670. .. versionchanged:: 1.7
  671. If you specify a ``max_length`` attribute, it will be reflected in the
  672. :class:`~django.forms.Textarea` widget of the auto-generated form field.
  673. However it is not enforced at the model or database level. Use a
  674. :class:`CharField` for that.
  675. .. admonition:: MySQL users
  676. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  677. collation (which is *not* the default), there are some issues to be aware
  678. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  679. details.
  680. ``TimeField``
  681. -------------
  682. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  683. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  684. auto-population options as :class:`DateField`.
  685. The default form widget for this field is a :class:`~django.forms.TextInput`.
  686. The admin adds some JavaScript shortcuts.
  687. ``URLField``
  688. ------------
  689. .. class:: URLField([max_length=200, **options])
  690. A :class:`CharField` for a URL.
  691. The default form widget for this field is a :class:`~django.forms.TextInput`.
  692. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  693. :attr:`~CharField.max_length` argument. If you don't specify
  694. :attr:`~CharField.max_length`, a default of 200 is used.
  695. Relationship fields
  696. ===================
  697. .. module:: django.db.models.fields.related
  698. :synopsis: Related field types
  699. .. currentmodule:: django.db.models
  700. Django also defines a set of fields that represent relations.
  701. .. _ref-foreignkey:
  702. ``ForeignKey``
  703. --------------
  704. .. class:: ForeignKey(othermodel, [**options])
  705. A many-to-one relationship. Requires a positional argument: the class to which
  706. the model is related.
  707. .. _recursive-relationships:
  708. To create a recursive relationship -- an object that has a many-to-one
  709. relationship with itself -- use ``models.ForeignKey('self')``.
  710. .. _lazy-relationships:
  711. If you need to create a relationship on a model that has not yet been defined,
  712. you can use the name of the model, rather than the model object itself::
  713. from django.db import models
  714. class Car(models.Model):
  715. manufacturer = models.ForeignKey('Manufacturer')
  716. # ...
  717. class Manufacturer(models.Model):
  718. # ...
  719. pass
  720. To refer to models defined in another application, you can explicitly specify
  721. a model with the full application label. For example, if the ``Manufacturer``
  722. model above is defined in another application called ``production``, you'd
  723. need to use::
  724. class Car(models.Model):
  725. manufacturer = models.ForeignKey('production.Manufacturer')
  726. This sort of reference can be useful when resolving circular import
  727. dependencies between two applications.
  728. A database index is automatically created on the ``ForeignKey``. You can
  729. disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
  730. avoid the overhead of an index if you are creating a foreign key for
  731. consistency rather than joins, or if you will be creating an alternative index
  732. like a partial or multiple column index.
  733. Database Representation
  734. ~~~~~~~~~~~~~~~~~~~~~~~
  735. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  736. database column name. In the above example, the database table for the ``Car``
  737. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  738. specifying :attr:`~Field.db_column`) However, your code should never have to
  739. deal with the database column name, unless you write custom SQL. You'll always
  740. deal with the field names of your model object.
  741. .. _foreign-key-arguments:
  742. Arguments
  743. ~~~~~~~~~
  744. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  745. define the details of how the relation works.
  746. .. attribute:: ForeignKey.limit_choices_to
  747. Sets a limit to the available choices for this field when this field is
  748. rendered using a ``ModelForm`` or the admin (by default, all objects
  749. in the queryset are available to choose). Either a dictionary, a
  750. :class:`~django.db.models.Q` object, or a callable returning a
  751. dictionary or :class:`~django.db.models.Q` object can be used.
  752. For example::
  753. staff_member = models.ForeignKey(User, limit_choices_to={'is_staff': True})
  754. causes the corresponding field on the ``ModelForm`` to list only ``Users``
  755. that have ``is_staff=True``. This may be helpful in the Django admin.
  756. The callable form can be helpful, for instance, when used in conjunction
  757. with the Python ``datetime`` module to limit selections by date range. For
  758. example::
  759. limit_choices_to = lambda: {'pub_date__lte': datetime.date.utcnow()}
  760. If ``limit_choices_to`` is or returns a :class:`Q object
  761. <django.db.models.Q>`, which is useful for :ref:`complex queries
  762. <complex-lookups-with-q>`, then it will only have an effect on the choices
  763. available in the admin when the field is not listed in
  764. :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the
  765. ``ModelAdmin`` for the model.
  766. .. versionchanged:: 1.7
  767. Previous versions of Django do not allow passing a callable as a value
  768. for ``limit_choices_to``.
  769. .. note::
  770. If a callable is used for ``limit_choices_to``, it will be invoked
  771. every time a new form is instantiated. It may also be invoked when a
  772. model is validated, for example by management commands or the admin.
  773. The admin constructs querysets to validate its form inputs in various
  774. edge cases multiple times, so there is a possibility your callable may
  775. be invoked several times.
  776. .. attribute:: ForeignKey.related_name
  777. The name to use for the relation from the related object back to this one.
  778. It's also the default value for :attr:`related_query_name` (the name to use
  779. for the reverse filter name from the target model). See the :ref:`related
  780. objects documentation <backwards-related-objects>` for a full explanation
  781. and example. Note that you must set this value when defining relations on
  782. :ref:`abstract models <abstract-base-classes>`; and when you do so
  783. :ref:`some special syntax <abstract-related-name>` is available.
  784. If you'd prefer Django not to create a backwards relation, set
  785. ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
  786. ensure that the ``User`` model won't have a backwards relation to this
  787. model::
  788. user = models.ForeignKey(User, related_name='+')
  789. .. attribute:: ForeignKey.related_query_name
  790. The name to use for the reverse filter name from the target model.
  791. Defaults to the value of :attr:`related_name` if it is set, otherwise it
  792. defaults to the name of the model::
  793. # Declare the ForeignKey with related_query_name
  794. class Tag(models.Model):
  795. article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
  796. name = models.CharField(max_length=255)
  797. # That's now the name of the reverse filter
  798. article_instance.filter(tag__name="important")
  799. .. attribute:: ForeignKey.to_field
  800. The field on the related object that the relation is to. By default, Django
  801. uses the primary key of the related object.
  802. .. attribute:: ForeignKey.db_constraint
  803. Controls whether or not a constraint should be created in the database for
  804. this foreign key. The default is ``True``, and that's almost certainly what
  805. you want; setting this to ``False`` can be very bad for data integrity.
  806. That said, here are some scenarios where you might want to do this:
  807. * You have legacy data that is not valid.
  808. * You're sharding your database.
  809. If this is set to ``False``, accessing a related object that doesn't exist
  810. will raise its ``DoesNotExist`` exception.
  811. .. attribute:: ForeignKey.on_delete
  812. When an object referenced by a :class:`ForeignKey` is deleted, Django by
  813. default emulates the behavior of the SQL constraint ``ON DELETE CASCADE``
  814. and also deletes the object containing the ``ForeignKey``. This behavior
  815. can be overridden by specifying the :attr:`on_delete` argument. For
  816. example, if you have a nullable :class:`ForeignKey` and you want it to be
  817. set null when the referenced object is deleted::
  818. user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
  819. The possible values for :attr:`~ForeignKey.on_delete` are found in
  820. :mod:`django.db.models`:
  821. * .. attribute:: CASCADE
  822. Cascade deletes; the default.
  823. * .. attribute:: PROTECT
  824. Prevent deletion of the referenced object by raising
  825. :exc:`~django.db.models.ProtectedError`, a subclass of
  826. :exc:`django.db.IntegrityError`.
  827. * .. attribute:: SET_NULL
  828. Set the :class:`ForeignKey` null; this is only possible if
  829. :attr:`~Field.null` is ``True``.
  830. * .. attribute:: SET_DEFAULT
  831. Set the :class:`ForeignKey` to its default value; a default for the
  832. :class:`ForeignKey` must be set.
  833. * .. function:: SET()
  834. Set the :class:`ForeignKey` to the value passed to
  835. :func:`~django.db.models.SET()`, or if a callable is passed in,
  836. the result of calling it. In most cases, passing a callable will be
  837. necessary to avoid executing queries at the time your models.py is
  838. imported::
  839. from django.db import models
  840. from django.contrib.auth.models import User
  841. def get_sentinel_user():
  842. return User.objects.get_or_create(username='deleted')[0]
  843. class MyModel(models.Model):
  844. user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
  845. * .. attribute:: DO_NOTHING
  846. Take no action. If your database backend enforces referential
  847. integrity, this will cause an :exc:`~django.db.IntegrityError` unless
  848. you manually add an SQL ``ON DELETE`` constraint to the database field
  849. (perhaps using :ref:`initial sql<initial-sql>`).
  850. .. attribute:: ForeignKey.swappable
  851. .. versionadded:: 1.7
  852. Controls the migration framework's reaction if this :class:`ForeignKey`
  853. is pointing at a swappable model. If it is ``True`` - the default -
  854. then if the :class:`ForeignKey` is pointing at a model which matches
  855. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  856. model setting) the relationship will be stored in the migration using
  857. a reference to the setting, not to the model directly.
  858. You only want to override this to be ``False`` if you are sure your
  859. model should always point towards the swapped-in model - for example,
  860. if it is a profile model designed specifically for your custom user model.
  861. If in doubt, leave it to its default of ``True``.
  862. .. _ref-manytomany:
  863. ``ManyToManyField``
  864. -------------------
  865. .. class:: ManyToManyField(othermodel, [**options])
  866. A many-to-many relationship. Requires a positional argument: the class to
  867. which the model is related, which works exactly the same as it does for
  868. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
  869. :ref:`lazy <lazy-relationships>` relationships.
  870. Related objects can be added, removed, or created with the field's
  871. :class:`~django.db.models.fields.related.RelatedManager`.
  872. Database Representation
  873. ~~~~~~~~~~~~~~~~~~~~~~~
  874. Behind the scenes, Django creates an intermediary join table to represent the
  875. many-to-many relationship. By default, this table name is generated using the
  876. name of the many-to-many field and the name of the table for the model that
  877. contains it. Since some databases don't support table names above a certain
  878. length, these table names will be automatically truncated to 64 characters and a
  879. uniqueness hash will be used. This means you might see table names like
  880. ``author_books_9cdf4``; this is perfectly normal. You can manually provide the
  881. name of the join table using the :attr:`~ManyToManyField.db_table` option.
  882. .. _manytomany-arguments:
  883. Arguments
  884. ~~~~~~~~~
  885. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  886. that control how the relationship functions.
  887. .. attribute:: ManyToManyField.related_name
  888. Same as :attr:`ForeignKey.related_name`.
  889. .. attribute:: ManyToManyField.related_query_name
  890. Same as :attr:`ForeignKey.related_query_name`.
  891. .. attribute:: ManyToManyField.limit_choices_to
  892. Same as :attr:`ForeignKey.limit_choices_to`.
  893. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  894. custom intermediate table specified using the
  895. :attr:`~ManyToManyField.through` parameter.
  896. .. attribute:: ManyToManyField.symmetrical
  897. Only used in the definition of ManyToManyFields on self. Consider the
  898. following model::
  899. from django.db import models
  900. class Person(models.Model):
  901. friends = models.ManyToManyField("self")
  902. When Django processes this model, it identifies that it has a
  903. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  904. ``person_set`` attribute to the ``Person`` class. Instead, the
  905. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  906. your friend, then you are my friend.
  907. If you do not want symmetry in many-to-many relationships with ``self``, set
  908. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  909. add the descriptor for the reverse relationship, allowing
  910. :class:`ManyToManyField` relationships to be non-symmetrical.
  911. .. attribute:: ManyToManyField.through
  912. Django will automatically generate a table to manage many-to-many
  913. relationships. However, if you want to manually specify the intermediary
  914. table, you can use the :attr:`~ManyToManyField.through` option to specify
  915. the Django model that represents the intermediate table that you want to
  916. use.
  917. The most common use for this option is when you want to associate
  918. :ref:`extra data with a many-to-many relationship
  919. <intermediary-manytomany>`.
  920. .. attribute:: ManyToManyField.through_fields
  921. .. versionadded:: 1.7
  922. Only used when a custom intermediary model is specified. Django will
  923. normally determine which fields of the intermediary model to use in order
  924. to establish a many-to-many relationship automatically. However,
  925. consider the following models::
  926. from django.db import models
  927. class Person(models.Model):
  928. name = models.CharField(max_length=50)
  929. class Group(models.Model):
  930. name = models.CharField(max_length=128)
  931. members = models.ManyToManyField(Person, through='Membership', through_fields=('group', 'person'))
  932. class Membership(models.Model):
  933. group = models.ForeignKey(Group)
  934. person = models.ForeignKey(Person)
  935. inviter = models.ForeignKey(Person, related_name="membership_invites")
  936. invite_reason = models.CharField(max_length=64)
  937. ``Membership`` has *two* foreign keys to ``Person`` (``person`` and
  938. ``inviter``), which makes the relationship ambiguous and Django can't know
  939. which one to use. In this case, you must explicitly specify which
  940. foreign keys Django should use using ``through_fields``, as in the example
  941. above.
  942. ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where
  943. ``field1`` is the name of the foreign key to the model the
  944. :class:`ManyToManyField` is defined on (``group`` in this case), and
  945. ``field2`` the name of the foreign key to the target model (``person``
  946. in this case).
  947. When you have more than one foreign key on an intermediary model to any
  948. (or even both) of the models participating in a many-to-many relationship,
  949. you *must* specify ``through_fields``. This also applies to
  950. :ref:`recursive relationships <recursive-relationships>`
  951. when an intermediary model is used and there are more than two
  952. foreign keys to the model, or you want to explicitly specify which two
  953. Django should use.
  954. Recursive relationships using an intermediary model are always defined as
  955. non-symmetrical -- that is, with :attr:`symmetrical=False <ManyToManyField.symmetrical>`
  956. -- therefore, there is the concept of a "source" and a "target". In that
  957. case ``'field1'`` will be treated as the "source" of the relationship and
  958. ``'field2'`` as the "target".
  959. .. attribute:: ManyToManyField.db_table
  960. The name of the table to create for storing the many-to-many data. If this
  961. is not provided, Django will assume a default name based upon the names of:
  962. the table for the model defining the relationship and the name of the field
  963. itself.
  964. .. attribute:: ManyToManyField.db_constraint
  965. Controls whether or not constraints should be created in the database for
  966. the foreign keys in the intermediary table. The default is ``True``, and
  967. that's almost certainly what you want; setting this to ``False`` can be
  968. very bad for data integrity. That said, here are some scenarios where you
  969. might want to do this:
  970. * You have legacy data that is not valid.
  971. * You're sharding your database.
  972. It is an error to pass both ``db_constraint`` and ``through``.
  973. .. attribute:: ManyToManyField.swappable
  974. .. versionadded:: 1.7
  975. Controls the migration framework's reaction if this :class:`ManyToManyField`
  976. is pointing at a swappable model. If it is ``True`` - the default -
  977. then if the :class:`ManyToManyField` is pointing at a model which matches
  978. the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
  979. model setting) the relationship will be stored in the migration using
  980. a reference to the setting, not to the model directly.
  981. You only want to override this to be ``False`` if you are sure your
  982. model should always point towards the swapped-in model - for example,
  983. if it is a profile model designed specifically for your custom user model.
  984. If in doubt, leave it to its default of ``True``.
  985. .. _ref-onetoone:
  986. ``OneToOneField``
  987. -----------------
  988. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  989. A one-to-one relationship. Conceptually, this is similar to a
  990. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  991. "reverse" side of the relation will directly return a single object.
  992. This is most useful as the primary key of a model which "extends"
  993. another model in some way; :ref:`multi-table-inheritance` is
  994. implemented by adding an implicit one-to-one relation from the child
  995. model to the parent model, for example.
  996. One positional argument is required: the class to which the model will be
  997. related. This works exactly the same as it does for :class:`ForeignKey`,
  998. including all the options regarding :ref:`recursive <recursive-relationships>`
  999. and :ref:`lazy <lazy-relationships>` relationships.
  1000. If you do not specify the :attr:`~ForeignKey.related_name` argument for
  1001. the ``OneToOneField``, Django will use the lower-case name of the current model
  1002. as default value.
  1003. With the following example::
  1004. from django.db import models
  1005. from django.contrib.auth.models import User
  1006. class MySpecialUser(models.Model):
  1007. user = models.OneToOneField(User)
  1008. supervisor = models.OneToOneField(User, related_name='supervisor_of')
  1009. your resulting ``User`` model will have the following attributes::
  1010. >>> user = User.objects.get(pk=1)
  1011. >>> hasattr(user, 'myspecialuser')
  1012. True
  1013. >>> hasattr(user, 'supervisor_of')
  1014. True
  1015. A ``DoesNotExist`` exception is raised when accessing the reverse relationship
  1016. if an entry in the related table doesn't exist. For example, if a user doesn't
  1017. have a supervisor designated by ``MySpecialUser``::
  1018. >>> user.supervisor_of
  1019. Traceback (most recent call last):
  1020. ...
  1021. DoesNotExist: User matching query does not exist.
  1022. .. _onetoone-arguments:
  1023. Additionally, ``OneToOneField`` accepts all of the extra arguments
  1024. accepted by :class:`ForeignKey`, plus one extra argument:
  1025. .. attribute:: OneToOneField.parent_link
  1026. When ``True`` and used in a model which inherits from another
  1027. (concrete) model, indicates that this field should be used as the
  1028. link back to the parent class, rather than the extra
  1029. ``OneToOneField`` which would normally be implicitly created by
  1030. subclassing.
  1031. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
  1032. examples of ``OneToOneField``.