fields.txt 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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 easily :doc:`write your
  11. own custom model fields </howto/custom-model-fields>`.
  12. .. note::
  13. Technically, these models are defined in :mod:`django.db.models.fields`, but
  14. for convenience they're imported into :mod:`django.db.models`; the standard
  15. convention is to use ``from django.db import models`` and refer to fields as
  16. ``models.<Foo>Field``.
  17. .. _common-model-field-options:
  18. Field options
  19. =============
  20. The following arguments are available to all field types. All are optional.
  21. ``null``
  22. --------
  23. .. attribute:: Field.null
  24. If ``True``, Django will store empty values as ``NULL`` in the database. Default
  25. is ``False``.
  26. Note that empty string values will always get stored as empty strings, not as
  27. ``NULL``. Only use ``null=True`` for non-string fields such as integers,
  28. booleans and dates. For both types of fields, you will also need to set
  29. ``blank=True`` if you wish to permit empty values in forms, as the
  30. :attr:`~Field.null` parameter only affects database storage (see
  31. :attr:`~Field.blank`).
  32. Avoid using :attr:`~Field.null` on string-based fields such as
  33. :class:`CharField` and :class:`TextField` unless you have an excellent reason.
  34. If a string-based field has ``null=True``, that means it has two possible values
  35. for "no data": ``NULL``, and the empty string. In most cases, it's redundant to
  36. have two possible values for "no data;" Django convention is to use the empty
  37. string, not ``NULL``.
  38. .. note::
  39. When using the Oracle database backend, the ``null=True`` option will be
  40. coerced for string-based fields that have the empty string as a possible
  41. value, and the value ``NULL`` will be stored to denote the empty string.
  42. ``blank``
  43. ---------
  44. .. attribute:: Field.blank
  45. If ``True``, the field is allowed to be blank. Default is ``False``.
  46. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  47. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  48. a field has ``blank=True``, validation on Django's admin site will allow entry
  49. of an empty value. If a field has ``blank=False``, the field will be required.
  50. .. _field-choices:
  51. ``choices``
  52. -----------
  53. .. attribute:: Field.choices
  54. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
  55. field.
  56. If this is given, Django's admin will use a select box instead of the standard
  57. text field and will limit choices to the choices given.
  58. A choices list looks like this::
  59. YEAR_IN_SCHOOL_CHOICES = (
  60. ('FR', 'Freshman'),
  61. ('SO', 'Sophomore'),
  62. ('JR', 'Junior'),
  63. ('SR', 'Senior'),
  64. ('GR', 'Graduate'),
  65. )
  66. The first element in each tuple is the actual value to be stored. The second
  67. element is the human-readable name for the option.
  68. The choices list can be defined either as part of your model class::
  69. class Foo(models.Model):
  70. GENDER_CHOICES = (
  71. ('M', 'Male'),
  72. ('F', 'Female'),
  73. )
  74. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  75. or outside your model class altogether::
  76. GENDER_CHOICES = (
  77. ('M', 'Male'),
  78. ('F', 'Female'),
  79. )
  80. class Foo(models.Model):
  81. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  82. You can also collect your available choices into named groups that can
  83. be used for organizational purposes::
  84. MEDIA_CHOICES = (
  85. ('Audio', (
  86. ('vinyl', 'Vinyl'),
  87. ('cd', 'CD'),
  88. )
  89. ),
  90. ('Video', (
  91. ('vhs', 'VHS Tape'),
  92. ('dvd', 'DVD'),
  93. )
  94. ),
  95. ('unknown', 'Unknown'),
  96. )
  97. The first element in each tuple is the name to apply to the group. The
  98. second element is an iterable of 2-tuples, with each 2-tuple containing
  99. a value and a human-readable name for an option. Grouped options may be
  100. combined with ungrouped options within a single list (such as the
  101. `unknown` option in this example).
  102. For each model field that has :attr:`~Field.choices` set, Django will add a
  103. method to retrieve the human-readable name for the field's current value. See
  104. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  105. documentation.
  106. Finally, note that choices can be any iterable object -- not necessarily a list
  107. or tuple. This lets you construct choices dynamically. But if you find yourself
  108. hacking :attr:`~Field.choices` to be dynamic, you're probably better off using a
  109. proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is
  110. meant for static data that doesn't change much, if ever.
  111. ``db_column``
  112. -------------
  113. .. attribute:: Field.db_column
  114. The name of the database column to use for this field. If this isn't given,
  115. Django will use the field's name.
  116. If your database column name is an SQL reserved word, or contains
  117. characters that aren't allowed in Python variable names -- notably, the
  118. hyphen -- that's OK. Django quotes column and table names behind the
  119. scenes.
  120. ``db_index``
  121. ------------
  122. .. attribute:: Field.db_index
  123. If ``True``, djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a
  124. ``CREATE INDEX`` statement for this field.
  125. ``db_tablespace``
  126. -----------------
  127. .. attribute:: Field.db_tablespace
  128. The name of the database tablespace to use for this field's index, if this field
  129. is indexed. The default is the project's :setting:`DEFAULT_INDEX_TABLESPACE`
  130. setting, if set, or the :attr:`~Field.db_tablespace` of the model, if any. If
  131. the backend doesn't support tablespaces, this option is ignored.
  132. ``default``
  133. -----------
  134. .. attribute:: Field.default
  135. The default value for the field. This can be a value or a callable object. If
  136. callable it will be called every time a new object is created.
  137. ``editable``
  138. ------------
  139. .. attribute:: Field.editable
  140. If ``False``, the field will not be editable in the admin or via forms
  141. automatically generated from the model class. Default is ``True``.
  142. ``error_messages``
  143. ------------------
  144. .. versionadded:: 1.2
  145. .. attribute:: Field.error_messages
  146. The ``error_messages`` argument lets you override the default messages that the
  147. field will raise. Pass in a dictionary with keys matching the error messages you
  148. want to override.
  149. ``help_text``
  150. -------------
  151. .. attribute:: Field.help_text
  152. Extra "help" text to be displayed under the field on the object's admin form.
  153. It's useful for documentation even if your object doesn't have an admin form.
  154. Note that this value is *not* HTML-escaped when it's displayed in the admin
  155. interface. This lets you include HTML in :attr:`~Field.help_text` if you so
  156. desire. For example::
  157. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  158. Alternatively you can use plain text and
  159. ``django.utils.html.escape()`` to escape any HTML special characters.
  160. ``primary_key``
  161. ---------------
  162. .. attribute:: Field.primary_key
  163. If ``True``, this field is the primary key for the model.
  164. If you don't specify ``primary_key=True`` for any fields in your model, Django
  165. will automatically add an :class:`IntegerField` to hold the primary key, so you
  166. don't need to set ``primary_key=True`` on any of your fields unless you want to
  167. override the default primary-key behavior. For more, see
  168. :ref:`automatic-primary-key-fields`.
  169. ``primary_key=True`` implies :attr:`null=False <Field.null>` and :attr:`unique=True <Field.unique>`.
  170. Only one primary key is allowed on an object.
  171. ``unique``
  172. ----------
  173. .. attribute:: Field.unique
  174. If ``True``, this field must be unique throughout the table.
  175. This is enforced at the database level and at the Django admin-form level. If
  176. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  177. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  178. :meth:`~django.db.models.Model.save` method.
  179. This option is valid on all field types except :class:`ManyToManyField` and
  180. :class:`FileField`.
  181. ``unique_for_date``
  182. -------------------
  183. .. attribute:: Field.unique_for_date
  184. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  185. require that this field be unique for the value of the date field.
  186. For example, if you have a field ``title`` that has
  187. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  188. records with the same ``title`` and ``pub_date``.
  189. This is enforced at the Django admin-form level but not at the database level.
  190. ``unique_for_month``
  191. --------------------
  192. .. attribute:: Field.unique_for_month
  193. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  194. respect to the month.
  195. ``unique_for_year``
  196. -------------------
  197. .. attribute:: Field.unique_for_year
  198. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  199. ``verbose_name``
  200. -------------------
  201. .. attribute:: Field.verbose_name
  202. A human-readable name for the field. If the verbose name isn't given, Django
  203. will automatically create it using the field's attribute name, converting
  204. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
  205. ``validators``
  206. -------------------
  207. .. versionadded:: 1.2
  208. .. attribute:: Field.validators
  209. A list of validators to run for this field.See the :doc:`validators
  210. documentation </ref/validators>` for more information.
  211. .. _model-field-types:
  212. Field types
  213. ===========
  214. .. currentmodule:: django.db.models
  215. ``AutoField``
  216. -------------
  217. .. class:: AutoField(**options)
  218. An :class:`IntegerField` that automatically increments
  219. according to available IDs. You usually won't need to use this directly; a
  220. primary key field will automatically be added to your model if you don't specify
  221. otherwise. See :ref:`automatic-primary-key-fields`.
  222. ``BigIntegerField``
  223. -------------------
  224. .. versionadded:: 1.2
  225. .. class:: BigIntegerField([**options])
  226. A 64 bit integer, much like an :class:`IntegerField` except that it is
  227. guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The
  228. admin represents this as an ``<input type="text">`` (a single-line input).
  229. ``BooleanField``
  230. ----------------
  231. .. class:: BooleanField(**options)
  232. A true/false field.
  233. The admin represents this as a checkbox.
  234. .. versionchanged:: 1.2
  235. In previous versions of Django when running under MySQL ``BooleanFields``
  236. would return their data as ``ints``, instead of true ``bools``. See the
  237. release notes for a complete description of the change.
  238. ``CharField``
  239. -------------
  240. .. class:: CharField(max_length=None, [**options])
  241. A string field, for small- to large-sized strings.
  242. For large amounts of text, use :class:`~django.db.models.TextField`.
  243. The admin represents this as an ``<input type="text">`` (a single-line input).
  244. :class:`CharField` has one extra required argument:
  245. .. attribute:: CharField.max_length
  246. The maximum length (in characters) of the field. The max_length is enforced
  247. at the database level and in Django's validation.
  248. .. note::
  249. If you are writing an application that must be portable to multiple
  250. database backends, you should be aware that there are restrictions on
  251. ``max_length`` for some backends. Refer to the :doc:`database backend
  252. notes </ref/databases>` for details.
  253. .. admonition:: MySQL users
  254. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  255. collation (which is *not* the default), there are some issues to be aware
  256. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  257. details.
  258. ``CommaSeparatedIntegerField``
  259. ------------------------------
  260. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  261. A field of integers separated by commas. As in :class:`CharField`, the
  262. :attr:`~CharField.max_length` argument is required and the note about database
  263. portability mentioned there should be heeded.
  264. ``DateField``
  265. -------------
  266. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  267. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  268. optional arguments:
  269. .. attribute:: DateField.auto_now
  270. Automatically set the field to now every time the object is saved. Useful
  271. for "last-modified" timestamps. Note that the current date is *always*
  272. used; it's not just a default value that you can override.
  273. .. attribute:: DateField.auto_now_add
  274. Automatically set the field to now when the object is first created. Useful
  275. for creation of timestamps. Note that the current date is *always* used;
  276. it's not just a default value that you can override.
  277. The admin represents this as an ``<input type="text">`` with a JavaScript
  278. calendar, and a shortcut for "Today". The JavaScript calendar will always
  279. start the week on a Sunday.
  280. .. note::
  281. As currently implemented, setting ``auto_now`` or ``auto_add_now`` to
  282. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  283. set.
  284. ``DateTimeField``
  285. -----------------
  286. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  287. A date and time, represented in Python by a ``datetime.datetime`` instance.
  288. Takes the same extra arguments as :class:`DateField`.
  289. The admin represents this as two ``<input type="text">`` fields, with
  290. JavaScript shortcuts.
  291. ``DecimalField``
  292. ----------------
  293. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  294. A fixed-precision decimal number, represented in Python by a
  295. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  296. .. attribute:: DecimalField.max_digits
  297. The maximum number of digits allowed in the number
  298. .. attribute:: DecimalField.decimal_places
  299. The number of decimal places to store with the number
  300. For example, to store numbers up to 999 with a resolution of 2 decimal places,
  301. you'd use::
  302. models.DecimalField(..., max_digits=5, decimal_places=2)
  303. And to store numbers up to approximately one billion with a resolution of 10
  304. decimal places::
  305. models.DecimalField(..., max_digits=19, decimal_places=10)
  306. The admin represents this as an ``<input type="text">`` (a single-line input).
  307. ``EmailField``
  308. --------------
  309. .. class:: EmailField([max_length=75, **options])
  310. A :class:`CharField` that checks that the value is a valid e-mail address.
  311. ``FileField``
  312. -------------
  313. .. class:: FileField(upload_to=None, [max_length=100, **options])
  314. A file-upload field.
  315. .. note::
  316. The ``primary_key`` and ``unique`` arguments are not supported, and will
  317. raise a ``TypeError`` if used.
  318. Has one **required** argument:
  319. .. attribute:: FileField.upload_to
  320. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  321. setting to determine the value of the :attr:`~django.core.files.File.url`
  322. attribute.
  323. This path may contain `strftime formatting`_, which will be replaced by the
  324. date/time of the file upload (so that uploaded files don't fill up the given
  325. directory).
  326. This may also be a callable, such as a function, which will be called to
  327. obtain the upload path, including the filename. This callable must be able
  328. to accept two arguments, and return a Unix-style path (with forward slashes)
  329. to be passed along to the storage system. The two arguments that will be
  330. passed are:
  331. ====================== ===============================================
  332. Argument Description
  333. ====================== ===============================================
  334. ``instance`` An instance of the model where the
  335. ``FileField`` is defined. More specifically,
  336. this is the particular instance where the
  337. current file is being attached.
  338. In most cases, this object will not have been
  339. saved to the database yet, so if it uses the
  340. default ``AutoField``, *it might not yet have a
  341. value for its primary key field*.
  342. ``filename`` The filename that was originally given to the
  343. file. This may or may not be taken into account
  344. when determining the final destination path.
  345. ====================== ===============================================
  346. Also has one optional argument:
  347. .. attribute:: FileField.storage
  348. Optional. A storage object, which handles the storage and retrieval of your
  349. files. See :doc:`/topics/files` for details on how to provide this object.
  350. The admin represents this field as an ``<input type="file">`` (a file-upload
  351. widget).
  352. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  353. takes a few steps:
  354. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  355. full path to a directory where you'd like Django to store uploaded files.
  356. (For performance, these files are not stored in the database.) Define
  357. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  358. that this directory is writable by the Web server's user account.
  359. 2. Add the :class:`FileField` or :class:`ImageField` to your model, making
  360. sure to define the :attr:`~FileField.upload_to` option to tell Django
  361. to which subdirectory of :setting:`MEDIA_ROOT` it should upload files.
  362. 3. All that will be stored in your database is a path to the file
  363. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  364. convenience :attr:`~django.core.files.File.url` function provided by
  365. Django. For example, if your :class:`ImageField` is called ``mug_shot``,
  366. you can get the absolute path to your image in a template with
  367. ``{{ object.mug_shot.url }}``.
  368. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  369. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  370. part of :attr:`~FileField.upload_to` is `strftime formatting`_; ``'%Y'`` is the
  371. four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is the two-digit
  372. day. If you upload a file on Jan. 15, 2007, it will be saved in the directory
  373. ``/home/media/photos/2007/01/15``.
  374. If you want to retrieve the upload file's on-disk filename, or a URL that refers
  375. to that file, or the file's size, you can use the
  376. :attr:`~django.core.files.File.name`, :attr:`~django.core.files.File.url`
  377. and :attr:`~django.core.files.File.size` attributes; see :doc:`/topics/files`.
  378. Note that whenever you deal with uploaded files, you should pay close attention
  379. to where you're uploading them and what type of files they are, to avoid
  380. security holes. *Validate all uploaded files* so that you're sure the files are
  381. what you think they are. For example, if you blindly let somebody upload files,
  382. without validation, to a directory that's within your Web server's document
  383. root, then somebody could upload a CGI or PHP script and execute that script by
  384. visiting its URL on your site. Don't allow that.
  385. By default, :class:`FileField` instances are
  386. created as ``varchar(100)`` columns in your database. As with other fields, you
  387. can change the maximum length using the :attr:`~CharField.max_length` argument.
  388. .. _`strftime formatting`: http://docs.python.org/library/time.html#time.strftime
  389. FileField and FieldFile
  390. ~~~~~~~~~~~~~~~~~~~~~~~
  391. When you access a :class:`FileField` on a model, you are given an instance
  392. of :class:`FieldFile` as a proxy for accessing the underlying file. This
  393. class has several methods that can be used to interact with file data:
  394. .. method:: FieldFile.open(mode='rb')
  395. Behaves like the standard Python ``open()`` method and opens the file
  396. associated with this instance in the mode specified by ``mode``.
  397. .. method:: FieldFile.close()
  398. Behaves like the standard Python ``file.close()`` method and closes the file
  399. associated with this instance.
  400. .. method:: FieldFile.save(name, content, save=True)
  401. This method takes a filename and file contents and passes them to the storage
  402. class for the field, then associates the stored file with the model field.
  403. If you want to manually associate file data with :class:`FileField`
  404. instances on your model, the ``save()`` method is used to persist that file
  405. data.
  406. Takes two required arguments: ``name`` which is the name of the file, and
  407. ``content`` which is a file-like object containing the file's contents. The
  408. optional ``save`` argument controls whether or not the instance is saved after
  409. the file has been altered. Defaults to ``True``.
  410. .. method:: FieldFile.delete(save=True)
  411. Deletes the file associated with this instance and clears all attributes on
  412. the field. Note: This method will close the file if it happens to be open when
  413. ``delete()`` is called.
  414. The optional ``save`` argument controls whether or not the instance is saved
  415. after the file has been deleted. Defaults to ``True``.
  416. ``FilePathField``
  417. -----------------
  418. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  419. A :class:`CharField` whose choices are limited to the filenames in a certain
  420. directory on the filesystem. Has three special arguments, of which the first is
  421. **required**:
  422. .. attribute:: FilePathField.path
  423. Required. The absolute filesystem path to a directory from which this
  424. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  425. .. attribute:: FilePathField.match
  426. Optional. A regular expression, as a string, that :class:`FilePathField`
  427. will use to filter filenames. Note that the regex will be applied to the
  428. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  429. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
  430. .. attribute:: FilePathField.recursive
  431. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  432. whether all subdirectories of :attr:`~FilePathField.path` should be included
  433. Of course, these arguments can be used together.
  434. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  435. base filename, not the full path. So, this example::
  436. FilePathField(path="/home/images", match="foo.*", recursive=True)
  437. ...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
  438. because the :attr:`~FilePathField.match` applies to the base filename
  439. (``foo.gif`` and ``bar.gif``).
  440. By default, :class:`FilePathField` instances are
  441. created as ``varchar(100)`` columns in your database. As with other fields, you
  442. can change the maximum length using the :attr:`~CharField.max_length` argument.
  443. ``FloatField``
  444. --------------
  445. .. class:: FloatField([**options])
  446. A floating-point number represented in Python by a ``float`` instance.
  447. The admin represents this as an ``<input type="text">`` (a single-line input).
  448. ``ImageField``
  449. --------------
  450. .. class:: ImageField(upload_to=None, [height_field=None, width_field=None, max_length=100, **options])
  451. Inherits all attributes and methods from :class:`FileField`, but also
  452. validates that the uploaded object is a valid image.
  453. In addition to the special attributes that are available for :class:`FileField`,
  454. an :class:`ImageField` also has :attr:`~django.core.files.File.height` and
  455. :attr:`~django.core.files.File.width` attributes.
  456. To facilitate querying on those attributes, :class:`ImageField` has two extra
  457. optional arguments:
  458. .. attribute:: ImageField.height_field
  459. Name of a model field which will be auto-populated with the height of the
  460. image each time the model instance is saved.
  461. .. attribute:: ImageField.width_field
  462. Name of a model field which will be auto-populated with the width of the
  463. image each time the model instance is saved.
  464. Requires the `Python Imaging Library`_.
  465. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  466. By default, :class:`ImageField` instances are created as ``varchar(100)``
  467. columns in your database. As with other fields, you can change the maximum
  468. length using the :attr:`~CharField.max_length` argument.
  469. ``IntegerField``
  470. ----------------
  471. .. class:: IntegerField([**options])
  472. An integer. The admin represents this as an ``<input type="text">`` (a
  473. single-line input).
  474. ``IPAddressField``
  475. ------------------
  476. .. class:: IPAddressField([**options])
  477. An IP address, in string format (e.g. "192.0.2.30"). The admin represents this
  478. as an ``<input type="text">`` (a single-line input).
  479. ``NullBooleanField``
  480. --------------------
  481. .. class:: NullBooleanField([**options])
  482. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  483. this instead of a :class:`BooleanField` with ``null=True``. The admin represents
  484. this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
  485. ``PositiveIntegerField``
  486. ------------------------
  487. .. class:: PositiveIntegerField([**options])
  488. Like an :class:`IntegerField`, but must be positive.
  489. ``PositiveSmallIntegerField``
  490. -----------------------------
  491. .. class:: PositiveSmallIntegerField([**options])
  492. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  493. (database-dependent) point.
  494. ``SlugField``
  495. -------------
  496. .. class:: SlugField([max_length=50, **options])
  497. :term:`Slug` is a newspaper term. A slug is a short label for something,
  498. containing only letters, numbers, underscores or hyphens. They're generally used
  499. in URLs.
  500. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  501. about database portability and :attr:`~CharField.max_length` in that section,
  502. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  503. default length of 50.
  504. Implies setting :attr:`Field.db_index` to ``True``.
  505. It is often useful to automatically prepopulate a SlugField based on the value
  506. of some other value. You can do this automatically in the admin using
  507. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  508. ``SmallIntegerField``
  509. ---------------------
  510. .. class:: SmallIntegerField([**options])
  511. Like an :class:`IntegerField`, but only allows values under a certain
  512. (database-dependent) point.
  513. ``TextField``
  514. -------------
  515. .. class:: TextField([**options])
  516. A large text field. The admin represents this as a ``<textarea>`` (a multi-line
  517. input).
  518. .. admonition:: MySQL users
  519. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  520. collation (which is *not* the default), there are some issues to be aware
  521. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  522. details.
  523. ``TimeField``
  524. -------------
  525. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  526. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  527. auto-population options as :class:`DateField`.
  528. The admin represents this as an ``<input type="text">`` with some JavaScript
  529. shortcuts.
  530. ``URLField``
  531. ------------
  532. .. class:: URLField([verify_exists=True, max_length=200, **options])
  533. A :class:`CharField` for a URL. Has one extra optional argument:
  534. .. attribute:: URLField.verify_exists
  535. If ``True`` (the default), the URL given will be checked for existence
  536. (i.e., the URL actually loads and doesn't give a 404 response).
  537. Note that when you're using the single-threaded development server,
  538. validating a URL being served by the same server will hang. This should not
  539. be a problem for multithreaded servers.
  540. The admin represents this as an ``<input type="text">`` (a single-line input).
  541. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  542. :attr:`~CharField.max_length`argument. If you don't specify
  543. :attr:`~CharField.max_length`, a default of 200 is used.
  544. ``XMLField``
  545. ------------
  546. .. class:: XMLField(schema_path=None, [**options])
  547. A :class:`TextField` that checks that the value is valid XML that matches a
  548. given schema. Takes one required argument:
  549. .. attribute:: schema_path
  550. The filesystem path to a RelaxNG_ schema against which to validate the
  551. field.
  552. .. _RelaxNG: http://www.relaxng.org/
  553. Relationship fields
  554. ===================
  555. .. module:: django.db.models.fields.related
  556. :synopsis: Related field types
  557. .. currentmodule:: django.db.models
  558. Django also defines a set of fields that represent relations.
  559. .. _ref-foreignkey:
  560. ``ForeignKey``
  561. --------------
  562. .. class:: ForeignKey(othermodel, [**options])
  563. A many-to-one relationship. Requires a positional argument: the class to which
  564. the model is related.
  565. .. _recursive-relationships:
  566. To create a recursive relationship -- an object that has a many-to-one
  567. relationship with itself -- use ``models.ForeignKey('self')``.
  568. .. _lazy-relationships:
  569. If you need to create a relationship on a model that has not yet been defined,
  570. you can use the name of the model, rather than the model object itself::
  571. class Car(models.Model):
  572. manufacturer = models.ForeignKey('Manufacturer')
  573. # ...
  574. class Manufacturer(models.Model):
  575. # ...
  576. To refer to models defined in another application, you can explicitly specify
  577. a model with the full application label. For example, if the ``Manufacturer``
  578. model above is defined in another application called ``production``, you'd
  579. need to use::
  580. class Car(models.Model):
  581. manufacturer = models.ForeignKey('production.Manufacturer')
  582. This sort of reference can be useful when resolving circular import
  583. dependencies between two applications.
  584. Database Representation
  585. ~~~~~~~~~~~~~~~~~~~~~~~
  586. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  587. database column name. In the above example, the database table for the ``Car``
  588. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  589. specifying :attr:`~Field.db_column`) However, your code should never have to
  590. deal with the database column name, unless you write custom SQL. You'll always
  591. deal with the field names of your model object.
  592. .. _foreign-key-arguments:
  593. Arguments
  594. ~~~~~~~~~
  595. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  596. define the details of how the relation works.
  597. .. attribute:: ForeignKey.limit_choices_to
  598. A dictionary of lookup arguments and values (see :doc:`/topics/db/queries`)
  599. that limit the available admin choices for this object. Use this with
  600. functions from the Python ``datetime`` module to limit choices of objects by
  601. date. For example::
  602. limit_choices_to = {'pub_date__lte': datetime.now}
  603. only allows the choice of related objects with a ``pub_date`` before the
  604. current date/time to be chosen.
  605. Instead of a dictionary this can also be a :class:`~django.db.models.Q`
  606. object for more :ref:`complex queries <complex-lookups-with-q>`. However,
  607. if ``limit_choices_to`` is a :class:`~django.db.models.Q` object then it
  608. will only have an effect on the choices available in the admin when the
  609. field is not listed in ``raw_id_fields`` in the ``ModelAdmin`` for the model.
  610. .. attribute:: ForeignKey.related_name
  611. The name to use for the relation from the related object back to this one.
  612. See the :ref:`related objects documentation <backwards-related-objects>` for
  613. a full explanation and example. Note that you must set this value
  614. when defining relations on :ref:`abstract models
  615. <abstract-base-classes>`; and when you do so
  616. :ref:`some special syntax <abstract-related-name>` is available.
  617. If you'd prefer Django didn't create a backwards relation, set ``related_name``
  618. to ``'+'``. For example, this will ensure that the ``User`` model won't get a
  619. backwards relation to this model::
  620. user = models.ForeignKey(User, related_name='+')
  621. .. attribute:: ForeignKey.to_field
  622. The field on the related object that the relation is to. By default, Django
  623. uses the primary key of the related object.
  624. .. versionadded:: 1.3
  625. .. attribute:: ForeignKey.on_delete
  626. When an object referenced by a :class:`ForeignKey` is deleted, Django by
  627. default emulates the behavior of the SQL constraint ``ON DELETE CASCADE``
  628. and also deletes the object containing the ``ForeignKey``. This behavior
  629. can be overridden by specifying the :attr:`on_delete` argument. For
  630. example, if you have a nullable :class:`ForeignKey` and you want it to be
  631. set null when the referenced object is deleted::
  632. user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
  633. The possible values for :attr:`on_delete` are found in
  634. :mod:`django.db.models`:
  635. * :attr:`~django.db.models.CASCADE`: Cascade deletes; the default.
  636. * :attr:`~django.db.models.PROTECT`: Prevent deletion of the referenced
  637. object by raising :exc:`django.db.IntegrityError`.
  638. * :attr:`~django.db.models.SET_NULL`: Set the :class:`ForeignKey` null;
  639. this is only possible if :attr:`null` is ``True``.
  640. * :attr:`~django.db.models.SET_DEFAULT`: Set the :class:`ForeignKey` to its
  641. default value; a default for the :class:`ForeignKey` must be set.
  642. * :func:`~django.db.models.SET()`: Set the :class:`ForeignKey` to the value
  643. passed to :func:`~django.db.models.SET()`, or if a callable is passed in,
  644. the result of calling it. In most cases, passing a callable will be
  645. necessary to avoid executing queries at the time your models.py is
  646. imported::
  647. def get_sentinel_user():
  648. return User.objects.get_or_create(username='deleted')[0]
  649. class MyModel(models.Model):
  650. user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
  651. * :attr:`~django.db.models.DO_NOTHING`: Take no action. If your database
  652. backend enforces referential integrity, this will cause an
  653. :exc:`~django.db.IntegrityError` unless you manually add a SQL ``ON
  654. DELETE`` constraint to the database field (perhaps using
  655. :ref:`initial sql<initial-sql>`).
  656. .. _ref-manytomany:
  657. ``ManyToManyField``
  658. -------------------
  659. .. class:: ManyToManyField(othermodel, [**options])
  660. A many-to-many relationship. Requires a positional argument: the class to which
  661. the model is related. This works exactly the same as it does for
  662. :class:`ForeignKey`, including all the options regarding :ref:`recursive
  663. <recursive-relationships>` and :ref:`lazy <lazy-relationships>` relationships.
  664. Database Representation
  665. ~~~~~~~~~~~~~~~~~~~~~~~
  666. Behind the scenes, Django creates an intermediary join table to
  667. represent the many-to-many relationship. By default, this table name
  668. is generated using the name of the many-to-many field and the model
  669. that contains it. Since some databases don't support table names above
  670. a certain length, these table names will be automatically truncated to
  671. 64 characters and a uniqueness hash will be used. This means you might
  672. see table names like ``author_books_9cdf4``; this is perfectly normal.
  673. You can manually provide the name of the join table using the
  674. :attr:`~ManyToManyField.db_table` option.
  675. .. _manytomany-arguments:
  676. Arguments
  677. ~~~~~~~~~
  678. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  679. that control how the relationship functions.
  680. .. attribute:: ManyToManyField.related_name
  681. Same as :attr:`ForeignKey.related_name`.
  682. .. attribute:: ManyToManyField.limit_choices_to
  683. Same as :attr:`ForeignKey.limit_choices_to`.
  684. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
  685. custom intermediate table specified using the
  686. :attr:`~ManyToManyField.through` parameter.
  687. .. attribute:: ManyToManyField.symmetrical
  688. Only used in the definition of ManyToManyFields on self. Consider the
  689. following model::
  690. class Person(models.Model):
  691. friends = models.ManyToManyField("self")
  692. When Django processes this model, it identifies that it has a
  693. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  694. ``person_set`` attribute to the ``Person`` class. Instead, the
  695. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  696. your friend, then you are my friend.
  697. If you do not want symmetry in many-to-many relationships with ``self``, set
  698. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  699. add the descriptor for the reverse relationship, allowing
  700. :class:`ManyToManyField` relationships to be non-symmetrical.
  701. .. attribute:: ManyToManyField.through
  702. Django will automatically generate a table to manage many-to-many
  703. relationships. However, if you want to manually specify the intermediary
  704. table, you can use the :attr:`~ManyToManyField.through` option to specify
  705. the Django model that represents the intermediate table that you want to
  706. use.
  707. The most common use for this option is when you want to associate
  708. :ref:`extra data with a many-to-many relationship
  709. <intermediary-manytomany>`.
  710. .. attribute:: ManyToManyField.db_table
  711. The name of the table to create for storing the many-to-many data. If this
  712. is not provided, Django will assume a default name based upon the names of
  713. the two tables being joined.
  714. .. _ref-onetoone:
  715. ``OneToOneField``
  716. -----------------
  717. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  718. A one-to-one relationship. Conceptually, this is similar to a
  719. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  720. "reverse" side of the relation will directly return a single object.
  721. This is most useful as the primary key of a model which "extends"
  722. another model in some way; :ref:`multi-table-inheritance` is
  723. implemented by adding an implicit one-to-one relation from the child
  724. model to the parent model, for example.
  725. One positional argument is required: the class to which the model will be
  726. related. This works exactly the same as it does for :class:`ForeignKey`,
  727. including all the options regarding :ref:`recursive <recursive-relationships>`
  728. and :ref:`lazy <lazy-relationships>` relationships.
  729. .. _onetoone-arguments:
  730. Additionally, ``OneToOneField`` accepts all of the extra arguments
  731. accepted by :class:`ForeignKey`, plus one extra argument:
  732. .. attribute:: OneToOneField.parent_link
  733. When ``True`` and used in a model which inherits from another
  734. (concrete) model, indicates that this field should be used as the
  735. link back to the parent class, rather than the extra
  736. ``OneToOneField`` which would normally be implicitly created by
  737. subclassing.