fields.txt 41 KB

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