PageRenderTime 296ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

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