fields.txt 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. Note that empty string values will always get stored as empty strings, not as
  29. ``NULL``. Only use ``null=True`` for non-string fields such as integers,
  30. booleans and dates. For both types of fields, you will also need to set
  31. ``blank=True`` if you wish to permit empty values in forms, as the
  32. :attr:`~Field.null` parameter only affects database storage (see
  33. :attr:`~Field.blank`).
  34. Avoid using :attr:`~Field.null` on string-based fields such as
  35. :class:`CharField` and :class:`TextField` unless you have an excellent reason.
  36. If a string-based field has ``null=True``, that means it has two possible values
  37. for "no data": ``NULL``, and the empty string. In most cases, it's redundant to
  38. have two possible values for "no data;" Django convention is to use the empty
  39. string, not ``NULL``.
  40. .. note::
  41. When using the Oracle database backend, the value ``NULL`` will be stored to
  42. denote the empty string regardless of this attribute.
  43. If you want to accept :attr:`~Field.null` values with :class:`BooleanField`,
  44. use :class:`NullBooleanField` instead.
  45. ``blank``
  46. ---------
  47. .. attribute:: Field.blank
  48. If ``True``, the field is allowed to be blank. Default is ``False``.
  49. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  50. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  51. a field has ``blank=True``, form validation will allow entry of an empty value.
  52. If a field has ``blank=False``, the field will be required.
  53. .. _field-choices:
  54. ``choices``
  55. -----------
  56. .. attribute:: Field.choices
  57. An iterable (e.g., a list or tuple) consisting itself of iterables of exactly
  58. two items (e.g. ``[(A, B), (A, B) ...]``) to use as choices for this field. If
  59. this is given, the default form widget will be a select box with these choices
  60. instead of the standard text field.
  61. The first element in each tuple is the actual value to be stored, and the
  62. second element is the human-readable name. For example::
  63. YEAR_IN_SCHOOL_CHOICES = (
  64. ('FR', 'Freshman'),
  65. ('SO', 'Sophomore'),
  66. ('JR', 'Junior'),
  67. ('SR', 'Senior'),
  68. )
  69. Generally, it's best to define choices inside a model class, and to
  70. define a suitably-named constant for each value::
  71. from django.db import models
  72. class Student(models.Model):
  73. FRESHMAN = 'FR'
  74. SOPHOMORE = 'SO'
  75. JUNIOR = 'JR'
  76. SENIOR = 'SR'
  77. YEAR_IN_SCHOOL_CHOICES = (
  78. (FRESHMAN, 'Freshman'),
  79. (SOPHOMORE, 'Sophomore'),
  80. (JUNIOR, 'Junior'),
  81. (SENIOR, 'Senior'),
  82. )
  83. year_in_school = models.CharField(max_length=2,
  84. choices=YEAR_IN_SCHOOL_CHOICES,
  85. default=FRESHMAN)
  86. def is_upperclass(self):
  87. return self.year_in_school in (self.JUNIOR, self.SENIOR)
  88. Though you can define a choices list outside of a model class and then
  89. refer to it, defining the choices and names for each choice inside the
  90. model class keeps all of that information with the class that uses it,
  91. and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
  92. will work anywhere that the ``Student`` model has been imported).
  93. You can also collect your available choices into named groups that can
  94. be used for organizational purposes::
  95. MEDIA_CHOICES = (
  96. ('Audio', (
  97. ('vinyl', 'Vinyl'),
  98. ('cd', 'CD'),
  99. )
  100. ),
  101. ('Video', (
  102. ('vhs', 'VHS Tape'),
  103. ('dvd', 'DVD'),
  104. )
  105. ),
  106. ('unknown', 'Unknown'),
  107. )
  108. The first element in each tuple is the name to apply to the group. The
  109. second element is an iterable of 2-tuples, with each 2-tuple containing
  110. a value and a human-readable name for an option. Grouped options may be
  111. combined with ungrouped options within a single list (such as the
  112. `unknown` option in this example).
  113. For each model field that has :attr:`~Field.choices` set, Django will add a
  114. method to retrieve the human-readable name for the field's current value. See
  115. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  116. documentation.
  117. Note that choices can be any iterable object -- not necessarily a list or tuple.
  118. This lets you construct choices dynamically. But if you find yourself hacking
  119. :attr:`~Field.choices` to be dynamic, you're probably better off using a proper
  120. database table with a :class:`ForeignKey`. :attr:`~Field.choices` is meant for
  121. static data that doesn't change much, if ever.
  122. .. versionadded:: 1.7
  123. Unless :attr:`blank=False<Field.blank>` is set on the field along with a
  124. :attr:`~Field.default` then a label containing ``"---------"`` will be rendered
  125. with the select box. To override this behavior, add a tuple to ``choices``
  126. containing ``None``; e.g. ``(None, 'Your String For Display')``.
  127. Alternatively, you can use an empty string instead of ``None`` where this makes
  128. sense - such as on a :class:`~django.db.models.CharField`.
  129. ``db_column``
  130. -------------
  131. .. attribute:: Field.db_column
  132. The name of the database column to use for this field. If this isn't given,
  133. Django will use the field's name.
  134. If your database column name is an SQL reserved word, or contains
  135. characters that aren't allowed in Python variable names -- notably, the
  136. hyphen -- that's OK. Django quotes column and table names behind the
  137. scenes.
  138. ``db_index``
  139. ------------
  140. .. attribute:: Field.db_index
  141. If ``True``, :djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a
  142. ``CREATE INDEX`` statement for this field.
  143. ``db_tablespace``
  144. -----------------
  145. .. attribute:: Field.db_tablespace
  146. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  147. this field's index, if this field is indexed. The default is the project's
  148. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
  149. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
  150. support tablespaces for indexes, this option is ignored.
  151. ``default``
  152. -----------
  153. .. attribute:: Field.default
  154. The default value for the field. This can be a value or a callable object. If
  155. callable it will be called every time a new object is created.
  156. The default cannot be a mutable object (model instance, list, set, etc.), as a
  157. reference to the same instance of that object would be used as the default
  158. value in all new model instances. Instead, wrap the desired default in a
  159. callable. For example, if you had a custom ``JSONField`` and wanted to specify
  160. a dictionary as the default, use a ``lambda`` as follows::
  161. contact_info = JSONField("ContactInfo", default=lambda:{"email": "to1@example.com"})
  162. ``editable``
  163. ------------
  164. .. attribute:: Field.editable
  165. If ``False``, the field will not be displayed in the admin or any other
  166. :class:`~django.forms.ModelForm`. Default is ``True``.
  167. ``error_messages``
  168. ------------------
  169. .. attribute:: Field.error_messages
  170. The ``error_messages`` argument lets you override the default messages that the
  171. field will raise. Pass in a dictionary with keys matching the error messages you
  172. want to override.
  173. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  174. and ``unique``. Additional error message keys are specified for each field in
  175. the `Field types`_ section below.
  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 `Python Imaging Library`_.
  587. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  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 favour 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. .. admonition:: MySQL users
  673. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  674. collation (which is *not* the default), there are some issues to be aware
  675. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  676. details.
  677. ``TimeField``
  678. -------------
  679. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  680. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  681. auto-population options as :class:`DateField`.
  682. The default form widget for this field is a :class:`~django.forms.TextInput`.
  683. The admin adds some JavaScript shortcuts.
  684. ``URLField``
  685. ------------
  686. .. class:: URLField([max_length=200, **options])
  687. A :class:`CharField` for a URL.
  688. The default form widget for this field is a :class:`~django.forms.TextInput`.
  689. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  690. :attr:`~CharField.max_length` argument. If you don't specify
  691. :attr:`~CharField.max_length`, a default of 200 is used.
  692. Relationship fields
  693. ===================
  694. .. module:: django.db.models.fields.related
  695. :synopsis: Related field types
  696. .. currentmodule:: django.db.models
  697. Django also defines a set of fields that represent relations.
  698. .. _ref-foreignkey:
  699. ``ForeignKey``
  700. --------------
  701. .. class:: ForeignKey(othermodel, [**options])
  702. A many-to-one relationship. Requires a positional argument: the class to which
  703. the model is related.
  704. .. _recursive-relationships:
  705. To create a recursive relationship -- an object that has a many-to-one
  706. relationship with itself -- use ``models.ForeignKey('self')``.
  707. .. _lazy-relationships:
  708. If you need to create a relationship on a model that has not yet been defined,
  709. you can use the name of the model, rather than the model object itself::
  710. from django.db import models
  711. class Car(models.Model):
  712. manufacturer = models.ForeignKey('Manufacturer')
  713. # ...
  714. class Manufacturer(models.Model):
  715. # ...
  716. pass
  717. To refer to models defined in another application, you can explicitly specify
  718. a model with the full application label. For example, if the ``Manufacturer``
  719. model above is defined in another application called ``production``, you'd
  720. need to use::
  721. class Car(models.Model):
  722. manufacturer = models.ForeignKey('production.Manufacturer')
  723. This sort of reference can be useful when resolving circular import
  724. dependencies between two applications.
  725. A database index is automatically created on the ``ForeignKey``. You can
  726. disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
  727. avoid the overhead of an index if you are creating a foreign key for
  728. consistency rather than joins, or if you will be creating an alternative index
  729. like a partial or multiple column index.
  730. Database Representation
  731. ~~~~~~~~~~~~~~~~~~~~~~~
  732. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  733. database column name. In the above example, the database table for the ``Car``
  734. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  735. specifying :attr:`~Field.db_column`) However, your code should never have to
  736. deal with the database column name, unless you write custom SQL. You'll always
  737. deal with the field names of your model object.
  738. .. _foreign-key-arguments:
  739. Arguments
  740. ~~~~~~~~~
  741. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  742. define the details of how the relation works.
  743. .. attribute:: ForeignKey.limit_choices_to
  744. A dictionary of lookup arguments and values (see :doc:`/topics/db/queries`)
  745. that limit the available admin or :class:`ModelForm <django.forms.ModelForm>`
  746. choices for this object. For example::
  747. staff_member = models.ForeignKey(User, limit_choices_to={'is_staff': True})
  748. causes the corresponding field on the ``ModelForm`` to list only ``Users``
  749. that have ``is_staff=True``.
  750. Instead of a dictionary this can also be a :class:`Q object
  751. <django.db.models.Q>` for more :ref:`complex queries
  752. <complex-lookups-with-q>`. However, if ``limit_choices_to`` is a :class:`Q
  753. object <django.db.models.Q>` then it will only have an effect on the
  754. choices available in the admin when the field is not listed in
  755. ``raw_id_fields`` in the ``ModelAdmin`` for the model.
  756. .. attribute:: ForeignKey.related_name
  757. The name to use for the relation from the related object back to this one.
  758. It's also the default value for :attr:`related_query_name` (the name to use
  759. for the reverse filter name from the target model). See the :ref:`related
  760. objects documentation <backwards-related-objects>` for a full explanation
  761. and example. Note that you must set this value when defining relations on
  762. :ref:`abstract models <abstract-base-classes>`; and when you do so
  763. :ref:`some special syntax <abstract-related-name>` is available.
  764. If you'd prefer Django not to create a backwards relation, set
  765. ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will
  766. ensure that the ``User`` model won't have a backwards relation to this
  767. model::
  768. user = models.ForeignKey(User, related_name='+')
  769. .. attribute:: ForeignKey.related_query_name
  770. .. versionadded:: 1.6
  771. The name to use for the reverse filter name from the target model.
  772. Defaults to the value of :attr:`related_name` if it is set, otherwise it
  773. defaults to the name of the model::
  774. # Declare the ForeignKey with related_query_name
  775. class Tag(models.Model):
  776. article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
  777. name = models.CharField(max_length=255)
  778. # That's now the name of the reverse filter
  779. article_instance.filter(tag__name="important")
  780. .. attribute:: ForeignKey.to_field
  781. The field on the related object that the relation is to. By default, Django
  782. uses the primary key of the related object.
  783. .. attribute:: ForeignKey.db_constraint
  784. .. versionadded:: 1.6
  785. Controls whether or not a constraint should be created in the database for
  786. this foreign key. The default is ``True``, and that's almost certainly what
  787. you want; setting this to ``False`` can be very bad for data integrity.
  788. That said, here are some scenarios where you might want to do this:
  789. * You have legacy data that is not valid.
  790. * You're sharding your database.
  791. If this is set to ``False``, accessing a related object that doesn't exist
  792. will raise its ``DoesNotExist`` exception.
  793. .. attribute:: ForeignKey.on_delete
  794. When an object referenced by a :class:`ForeignKey` is deleted, Django by
  795. default emulates the behavior of the SQL constraint ``ON DELETE CASCADE``
  796. and also deletes the object containing the ``ForeignKey``. This behavior
  797. can be overridden by specifying the :attr:`on_delete` argument. For
  798. example, if you have a nullable :class:`ForeignKey` and you want it to be
  799. set null when the referenced object is deleted::
  800. user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
  801. The possible values for :attr:`~ForeignKey.on_delete` are found in
  802. :mod:`django.db.models`:
  803. * .. attribute:: CASCADE
  804. Cascade deletes; the default.
  805. * .. attribute:: PROTECT
  806. Prevent deletion of the referenced object by raising
  807. :exc:`~django.db.models.ProtectedError`, a subclass of
  808. :exc:`django.db.IntegrityError`.
  809. * .. attribute:: SET_NULL
  810. Set the :class:`ForeignKey` null; this is only possible if
  811. :attr:`~Field.null` is ``True``.
  812. * .. attribute:: SET_DEFAULT
  813. Set the :class:`ForeignKey` to its default value; a default for the
  814. :class:`ForeignKey` must be set.
  815. * .. function:: SET()
  816. Set the :class:`ForeignKey` to the value passed to
  817. :func:`~django.db.models.SET()`, or if a callable is passed in,
  818. the result of calling it. In most cases, passing a callable will be
  819. necessary to avoid executing queries at the time your models.py is
  820. imported::
  821. from django.db import models
  822. from django.contrib.auth.models import User
  823. def get_sentinel_user():
  824. return User.objects.get_or_create(username='deleted')[0]
  825. class MyModel(models.Model):
  826. user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
  827. * .. attribute:: DO_NOTHING
  828. Take no action. If your database backend enforces referential
  829. integrity, this will cause an :exc:`~django.db.IntegrityError` unless
  830. you manually add an SQL ``ON DELETE`` constraint to the database field
  831. (perhaps using :ref:`initial sql<initial-sql>`).
  832. .. _ref-manytomany:
  833. ``ManyToManyField``
  834. -------------------
  835. .. class:: ManyToManyField(othermodel, [**options])
  836. A many-to-many relationship. Requires a positional argument: the class to
  837. which the model is related, which works exactly the same as it does for
  838. :class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and
  839. :ref:`lazy <lazy-relationships>` relationships.
  840. Related objects can be added, removed, or created with the field's
  841. :class:`~django.db.models.fields.related.RelatedManager`.
  842. Database Representation
  843. ~~~~~~~~~~~~~~~~~~~~~~~
  844. Behind the scenes, Django creates an intermediary join table to represent the
  845. many-to-many relationship. By default, this table name is generated using the
  846. name of the many-to-many field and the name of the table for the model that
  847. contains it. Since some databases don't support table names above a certain
  848. length, these table names will be automatically truncated to 64 characters and a
  849. uniqueness hash will be used. This means you might see table names like
  850. ``author_books_9cdf4``; this is perfectly normal. You can manually provide the
  851. name of the join table using the :attr:`~ManyToManyField.db_table` option.
  852. .. _manytomany-arguments:
  853. Arguments
  854. ~~~~~~~~~
  855. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  856. that control how the relationship functions.
  857. .. attribute:: ManyToManyField.related_name
  858. Same as :attr:`ForeignKey.related_name`.
  859. .. attribute:: ManyToManyField.related_query_name
  860. .. versionadded:: 1.6
  861. Same as :attr:`ForeignKey.related_query_name`.
  862. .. attribute:: ManyToManyField.limit_choices_to
  863. Same as :attr:`ForeignKey.limit_choices_to`.
  864. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  865. custom intermediate table specified using the
  866. :attr:`~ManyToManyField.through` parameter.
  867. .. attribute:: ManyToManyField.symmetrical
  868. Only used in the definition of ManyToManyFields on self. Consider the
  869. following model::
  870. from django.db import models
  871. class Person(models.Model):
  872. friends = models.ManyToManyField("self")
  873. When Django processes this model, it identifies that it has a
  874. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  875. ``person_set`` attribute to the ``Person`` class. Instead, the
  876. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  877. your friend, then you are my friend.
  878. If you do not want symmetry in many-to-many relationships with ``self``, set
  879. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  880. add the descriptor for the reverse relationship, allowing
  881. :class:`ManyToManyField` relationships to be non-symmetrical.
  882. .. attribute:: ManyToManyField.through
  883. Django will automatically generate a table to manage many-to-many
  884. relationships. However, if you want to manually specify the intermediary
  885. table, you can use the :attr:`~ManyToManyField.through` option to specify
  886. the Django model that represents the intermediate table that you want to
  887. use.
  888. The most common use for this option is when you want to associate
  889. :ref:`extra data with a many-to-many relationship
  890. <intermediary-manytomany>`.
  891. .. attribute:: ManyToManyField.db_table
  892. The name of the table to create for storing the many-to-many data. If this
  893. is not provided, Django will assume a default name based upon the names of:
  894. the table for the model defining the relationship and the name of the field
  895. itself.
  896. .. attribute:: ManyToManyField.db_constraint
  897. .. versionadded:: 1.6
  898. Controls whether or not constraints should be created in the database for
  899. the foreign keys in the intermediary table. The default is ``True``, and
  900. that's almost certainly what you want; setting this to ``False`` can be
  901. very bad for data integrity. That said, here are some scenarios where you
  902. might want to do this:
  903. * You have legacy data that is not valid.
  904. * You're sharding your database.
  905. It is an error to pass both ``db_constraint`` and ``through``.
  906. .. _ref-onetoone:
  907. ``OneToOneField``
  908. -----------------
  909. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  910. A one-to-one relationship. Conceptually, this is similar to a
  911. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  912. "reverse" side of the relation will directly return a single object.
  913. This is most useful as the primary key of a model which "extends"
  914. another model in some way; :ref:`multi-table-inheritance` is
  915. implemented by adding an implicit one-to-one relation from the child
  916. model to the parent model, for example.
  917. One positional argument is required: the class to which the model will be
  918. related. This works exactly the same as it does for :class:`ForeignKey`,
  919. including all the options regarding :ref:`recursive <recursive-relationships>`
  920. and :ref:`lazy <lazy-relationships>` relationships.
  921. If you do not specify the :attr:`~ForeignKey.related_name` argument for
  922. the ``OneToOneField``, Django will use the lower-case name of the current model
  923. as default value.
  924. With the following example::
  925. from django.db import models
  926. from django.contrib.auth.models import User
  927. class MySpecialUser(models.Model):
  928. user = models.OneToOneField(User)
  929. supervisor = models.OneToOneField(User, related_name='supervisor_of')
  930. your resulting ``User`` model will have the following attributes::
  931. >>> user = User.objects.get(pk=1)
  932. >>> hasattr(user, 'myspecialuser')
  933. True
  934. >>> hasattr(user, 'supervisor_of')
  935. True
  936. .. _onetoone-arguments:
  937. Additionally, ``OneToOneField`` accepts all of the extra arguments
  938. accepted by :class:`ForeignKey`, plus one extra argument:
  939. .. attribute:: OneToOneField.parent_link
  940. When ``True`` and used in a model which inherits from another
  941. (concrete) model, indicates that this field should be used as the
  942. link back to the parent class, rather than the extra
  943. ``OneToOneField`` which would normally be implicitly created by
  944. subclassing.
  945. See :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage
  946. examples of ``OneToOneField``.