fields.txt 63 KB

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