fields.txt 51 KB

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