fields.txt 48 KB

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