fields.txt 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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 value ``NULL`` will be stored to
  42. denote the empty string regardless of this attribute.
  43. If you want to accept :attr:`~Field.null` values with :class:`BooleanField`,
  44. use :class:`NullBooleanField` instead.
  45. ``blank``
  46. ---------
  47. .. attribute:: Field.blank
  48. If ``True``, the field is allowed to be blank. Default is ``False``.
  49. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  50. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  51. a field has ``blank=True``, validation on Django's admin site will allow entry
  52. of an empty value. If a field has ``blank=False``, the field will be required.
  53. .. _field-choices:
  54. ``choices``
  55. -----------
  56. .. attribute:: Field.choices
  57. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
  58. field.
  59. If this is given, Django's admin will use a select box instead of the standard
  60. text field and will limit choices to the choices given.
  61. A choices list looks like this::
  62. YEAR_IN_SCHOOL_CHOICES = (
  63. ('FR', 'Freshman'),
  64. ('SO', 'Sophomore'),
  65. ('JR', 'Junior'),
  66. ('SR', 'Senior'),
  67. ('GR', 'Graduate'),
  68. )
  69. The first element in each tuple is the actual value to be stored. The second
  70. element is the human-readable name for the option.
  71. The choices list can be defined either as part of your model class::
  72. class Foo(models.Model):
  73. YEAR_IN_SCHOOL_CHOICES = (
  74. ('FR', 'Freshman'),
  75. ('SO', 'Sophomore'),
  76. ('JR', 'Junior'),
  77. ('SR', 'Senior'),
  78. ('GR', 'Graduate'),
  79. )
  80. year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)
  81. or outside your model class altogether::
  82. YEAR_IN_SCHOOL_CHOICES = (
  83. ('FR', 'Freshman'),
  84. ('SO', 'Sophomore'),
  85. ('JR', 'Junior'),
  86. ('SR', 'Senior'),
  87. ('GR', 'Graduate'),
  88. )
  89. class Foo(models.Model):
  90. year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)
  91. You can also collect your available choices into named groups that can
  92. be used for organizational purposes::
  93. MEDIA_CHOICES = (
  94. ('Audio', (
  95. ('vinyl', 'Vinyl'),
  96. ('cd', 'CD'),
  97. )
  98. ),
  99. ('Video', (
  100. ('vhs', 'VHS Tape'),
  101. ('dvd', 'DVD'),
  102. )
  103. ),
  104. ('unknown', 'Unknown'),
  105. )
  106. The first element in each tuple is the name to apply to the group. The
  107. second element is an iterable of 2-tuples, with each 2-tuple containing
  108. a value and a human-readable name for an option. Grouped options may be
  109. combined with ungrouped options within a single list (such as the
  110. `unknown` option in this example).
  111. For each model field that has :attr:`~Field.choices` set, Django will add a
  112. method to retrieve the human-readable name for the field's current value. See
  113. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  114. documentation.
  115. Finally, note that choices can be any iterable object -- not necessarily a list
  116. or tuple. This lets you construct choices dynamically. But if you find yourself
  117. hacking :attr:`~Field.choices` to be dynamic, you're probably better off using a
  118. proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is
  119. meant for static data that doesn't change much, if ever.
  120. ``db_column``
  121. -------------
  122. .. attribute:: Field.db_column
  123. The name of the database column to use for this field. If this isn't given,
  124. Django will use the field's name.
  125. If your database column name is an SQL reserved word, or contains
  126. characters that aren't allowed in Python variable names -- notably, the
  127. hyphen -- that's OK. Django quotes column and table names behind the
  128. scenes.
  129. ``db_index``
  130. ------------
  131. .. attribute:: Field.db_index
  132. If ``True``, djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a
  133. ``CREATE INDEX`` statement for this field.
  134. ``db_tablespace``
  135. -----------------
  136. .. attribute:: Field.db_tablespace
  137. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  138. this field's index, if this field is indexed. The default is the project's
  139. :setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
  140. :attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
  141. support tablespaces for indexes, this option is ignored.
  142. ``default``
  143. -----------
  144. .. attribute:: Field.default
  145. The default value for the field. This can be a value or a callable object. If
  146. callable it will be called every time a new object is created.
  147. ``editable``
  148. ------------
  149. .. attribute:: Field.editable
  150. If ``False``, the field will not be editable in the admin or via forms
  151. automatically generated from the model class. Default is ``True``.
  152. ``error_messages``
  153. ------------------
  154. .. attribute:: Field.error_messages
  155. The ``error_messages`` argument lets you override the default messages that the
  156. field will raise. Pass in a dictionary with keys matching the error messages you
  157. want to override.
  158. Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  159. and ``unique``. Additional error message keys are specified for each field in
  160. the `Field types`_ section below.
  161. ``help_text``
  162. -------------
  163. .. attribute:: Field.help_text
  164. Extra "help" text to be displayed under the field on the object's admin form.
  165. It's useful for documentation even if your object doesn't have an admin form.
  166. Note that this value is *not* HTML-escaped when it's displayed in the admin
  167. interface. This lets you include HTML in :attr:`~Field.help_text` if you so
  168. desire. For example::
  169. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  170. Alternatively you can use plain text and
  171. ``django.utils.html.escape()`` to escape any HTML special characters.
  172. ``primary_key``
  173. ---------------
  174. .. attribute:: Field.primary_key
  175. If ``True``, this field is the primary key for the model.
  176. If you don't specify ``primary_key=True`` for any fields in your model, Django
  177. will automatically add an :class:`IntegerField` to hold the primary key, so you
  178. don't need to set ``primary_key=True`` on any of your fields unless you want to
  179. override the default primary-key behavior. For more, see
  180. :ref:`automatic-primary-key-fields`.
  181. ``primary_key=True`` implies :attr:`null=False <Field.null>` and :attr:`unique=True <Field.unique>`.
  182. Only one primary key is allowed on an object.
  183. ``unique``
  184. ----------
  185. .. attribute:: Field.unique
  186. If ``True``, this field must be unique throughout the table.
  187. This is enforced at the database level and at the Django admin-form level. If
  188. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  189. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  190. :meth:`~django.db.models.Model.save` method.
  191. This option is valid on all field types except :class:`ManyToManyField` and
  192. :class:`FileField`.
  193. ``unique_for_date``
  194. -------------------
  195. .. attribute:: Field.unique_for_date
  196. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  197. require that this field be unique for the value of the date field.
  198. For example, if you have a field ``title`` that has
  199. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  200. records with the same ``title`` and ``pub_date``.
  201. This is enforced at the Django admin-form level but not at the database level.
  202. ``unique_for_month``
  203. --------------------
  204. .. attribute:: Field.unique_for_month
  205. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  206. respect to the month.
  207. ``unique_for_year``
  208. -------------------
  209. .. attribute:: Field.unique_for_year
  210. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  211. ``verbose_name``
  212. -------------------
  213. .. attribute:: Field.verbose_name
  214. A human-readable name for the field. If the verbose name isn't given, Django
  215. will automatically create it using the field's attribute name, converting
  216. underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
  217. ``validators``
  218. -------------------
  219. .. attribute:: Field.validators
  220. A list of validators to run for this field. See the :doc:`validators
  221. documentation </ref/validators>` for more information.
  222. .. _model-field-types:
  223. Field types
  224. ===========
  225. .. currentmodule:: django.db.models
  226. ``AutoField``
  227. -------------
  228. .. class:: AutoField(**options)
  229. An :class:`IntegerField` that automatically increments
  230. according to available IDs. You usually won't need to use this directly; a
  231. primary key field will automatically be added to your model if you don't specify
  232. otherwise. See :ref:`automatic-primary-key-fields`.
  233. ``BigIntegerField``
  234. -------------------
  235. .. class:: BigIntegerField([**options])
  236. A 64 bit integer, much like an :class:`IntegerField` except that it is
  237. guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The
  238. admin represents this as an ``<input type="text">`` (a single-line input).
  239. ``BooleanField``
  240. ----------------
  241. .. class:: BooleanField(**options)
  242. A true/false field.
  243. The admin represents this as a checkbox.
  244. If you need to accept :attr:`~Field.null` values then use
  245. :class:`NullBooleanField` instead.
  246. ``CharField``
  247. -------------
  248. .. class:: CharField(max_length=None, [**options])
  249. A string field, for small- to large-sized strings.
  250. For large amounts of text, use :class:`~django.db.models.TextField`.
  251. The admin represents this as an ``<input type="text">`` (a single-line input).
  252. :class:`CharField` has one extra required argument:
  253. .. attribute:: CharField.max_length
  254. The maximum length (in characters) of the field. The max_length is enforced
  255. at the database level and in Django's validation.
  256. .. note::
  257. If you are writing an application that must be portable to multiple
  258. database backends, you should be aware that there are restrictions on
  259. ``max_length`` for some backends. Refer to the :doc:`database backend
  260. notes </ref/databases>` for details.
  261. .. admonition:: MySQL users
  262. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  263. collation (which is *not* the default), there are some issues to be aware
  264. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  265. details.
  266. ``CommaSeparatedIntegerField``
  267. ------------------------------
  268. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  269. A field of integers separated by commas. As in :class:`CharField`, the
  270. :attr:`~CharField.max_length` argument is required and the note about database
  271. portability mentioned there should be heeded.
  272. ``DateField``
  273. -------------
  274. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  275. A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
  276. optional arguments:
  277. .. attribute:: DateField.auto_now
  278. Automatically set the field to now every time the object is saved. Useful
  279. for "last-modified" timestamps. Note that the current date is *always*
  280. used; it's not just a default value that you can override.
  281. .. attribute:: DateField.auto_now_add
  282. Automatically set the field to now when the object is first created. Useful
  283. for creation of timestamps. Note that the current date is *always* used;
  284. it's not just a default value that you can override.
  285. The admin represents this as an ``<input type="text">`` with a JavaScript
  286. calendar, and a shortcut for "Today". Includes an additional ``invalid_date``
  287. error message key.
  288. .. note::
  289. As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
  290. ``True`` will cause the field to have ``editable=False`` and ``blank=True``
  291. set.
  292. ``DateTimeField``
  293. -----------------
  294. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  295. A date and time, represented in Python by a ``datetime.datetime`` instance.
  296. Takes the same extra arguments as :class:`DateField`.
  297. The admin represents this as two ``<input type="text">`` fields, with
  298. JavaScript shortcuts.
  299. ``DecimalField``
  300. ----------------
  301. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  302. A fixed-precision decimal number, represented in Python by a
  303. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  304. .. attribute:: DecimalField.max_digits
  305. The maximum number of digits allowed in the number. Note that this number
  306. must be greater than or equal to ``decimal_places``, if it exists.
  307. .. attribute:: DecimalField.decimal_places
  308. The number of decimal places to store with the number.
  309. For example, to store numbers up to 999 with a resolution of 2 decimal places,
  310. you'd use::
  311. models.DecimalField(..., max_digits=5, decimal_places=2)
  312. And to store numbers up to approximately one billion with a resolution of 10
  313. decimal places::
  314. models.DecimalField(..., max_digits=19, decimal_places=10)
  315. The admin represents this as an ``<input type="text">`` (a single-line input).
  316. .. note::
  317. For more information about the differences between the
  318. :class:`FloatField` and :class:`DecimalField` classes, please
  319. see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`.
  320. ``EmailField``
  321. --------------
  322. .. class:: EmailField([max_length=75, **options])
  323. A :class:`CharField` that checks that the value is a valid email address.
  324. .. admonition:: Incompliance to RFCs
  325. The default 75 character ``max_length`` is not capable of storing all
  326. possible RFC3696/5321-compliant email addresses. In order to store all
  327. possible valid email addresses, a ``max_length`` of 254 is required.
  328. The default ``max_length`` of 75 exists for historical reasons. The
  329. default has not been changed in order to maintain backwards
  330. compatibility with existing uses of :class:`EmailField`.
  331. ``FileField``
  332. -------------
  333. .. class:: FileField(upload_to=None, [max_length=100, **options])
  334. A file-upload field.
  335. .. note::
  336. The ``primary_key`` and ``unique`` arguments are not supported, and will
  337. raise a ``TypeError`` if used.
  338. Has one **required** argument:
  339. .. attribute:: FileField.upload_to
  340. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  341. setting to determine the value of the :attr:`~django.core.files.File.url`
  342. attribute.
  343. This path may contain :func:`~time.strftime` formatting, which will be
  344. replaced by the date/time of the file upload (so that uploaded files don't
  345. fill up the given directory).
  346. This may also be a callable, such as a function, which will be called to
  347. obtain the upload path, including the filename. This callable must be able
  348. to accept two arguments, and return a Unix-style path (with forward slashes)
  349. to be passed along to the storage system. The two arguments that will be
  350. passed are:
  351. ====================== ===============================================
  352. Argument Description
  353. ====================== ===============================================
  354. ``instance`` An instance of the model where the
  355. ``FileField`` is defined. More specifically,
  356. this is the particular instance where the
  357. current file is being attached.
  358. In most cases, this object will not have been
  359. saved to the database yet, so if it uses the
  360. default ``AutoField``, *it might not yet have a
  361. value for its primary key field*.
  362. ``filename`` The filename that was originally given to the
  363. file. This may or may not be taken into account
  364. when determining the final destination path.
  365. ====================== ===============================================
  366. Also has one optional argument:
  367. .. attribute:: FileField.storage
  368. Optional. A storage object, which handles the storage and retrieval of your
  369. files. See :doc:`/topics/files` for details on how to provide this object.
  370. The admin represents this field as an ``<input type="file">`` (a file-upload
  371. widget).
  372. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  373. takes a few steps:
  374. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  375. full path to a directory where you'd like Django to store uploaded files.
  376. (For performance, these files are not stored in the database.) Define
  377. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  378. that this directory is writable by the Web server's user account.
  379. 2. Add the :class:`FileField` or :class:`ImageField` to your model, making
  380. sure to define the :attr:`~FileField.upload_to` option to tell Django
  381. to which subdirectory of :setting:`MEDIA_ROOT` it should upload files.
  382. 3. All that will be stored in your database is a path to the file
  383. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  384. convenience :attr:`~django.core.files.File.url` function provided by
  385. Django. For example, if your :class:`ImageField` is called ``mug_shot``,
  386. you can get the absolute path to your image in a template with
  387. ``{{ object.mug_shot.url }}``.
  388. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  389. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  390. part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
  391. ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
  392. the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
  393. the directory ``/home/media/photos/2007/01/15``.
  394. If you wanted to retrieve the uploaded file's on-disk filename, or the file's
  395. size, you could use the :attr:`~django.core.files.File.name` and
  396. :attr:`~django.core.files.File.size` attributes respectively; for more
  397. information on the available attributes and methods, see the
  398. :class:`~django.core.files.File` class reference and the :doc:`/topics/files`
  399. topic guide.
  400. .. note::
  401. The file is saved as part of saving the model in the database, so the actual
  402. file name used on disk cannot be relied on until after the model has been
  403. saved.
  404. The uploaded file's relative URL can be obtained using the
  405. :attr:`~django.db.models.fields.FileField.url` attribute. Internally,
  406. this calls the :meth:`~django.core.files.storage.Storage.url` method of the
  407. underlying :class:`~django.core.files.storage.Storage` class.
  408. .. _file-upload-security:
  409. Note that whenever you deal with uploaded files, you should pay close attention
  410. to where you're uploading them and what type of files they are, to avoid
  411. security holes. *Validate all uploaded files* so that you're sure the files are
  412. what you think they are. For example, if you blindly let somebody upload files,
  413. without validation, to a directory that's within your Web server's document
  414. root, then somebody could upload a CGI or PHP script and execute that script by
  415. visiting its URL on your site. Don't allow that.
  416. Also note that even an uploaded HTML file, since it can be executed by the
  417. browser (though not by the server), can pose security threats that are
  418. equivalent to XSS or CSRF attacks.
  419. By default, :class:`FileField` instances are
  420. created as ``varchar(100)`` columns in your database. As with other fields, you
  421. can change the maximum length using the :attr:`~CharField.max_length` argument.
  422. FileField and FieldFile
  423. ~~~~~~~~~~~~~~~~~~~~~~~
  424. When you access a :class:`FileField` on a model, you are given an instance
  425. of :class:`FieldFile` as a proxy for accessing the underlying file. This
  426. class has several methods that can be used to interact with file data:
  427. .. method:: FieldFile.open(mode='rb')
  428. Behaves like the standard Python ``open()`` method and opens the file
  429. associated with this instance in the mode specified by ``mode``.
  430. .. method:: FieldFile.close()
  431. Behaves like the standard Python ``file.close()`` method and closes the file
  432. associated with this instance.
  433. .. method:: FieldFile.save(name, content, save=True)
  434. This method takes a filename and file contents and passes them to the storage
  435. class for the field, then associates the stored file with the model field.
  436. If you want to manually associate file data with :class:`FileField`
  437. instances on your model, the ``save()`` method is used to persist that file
  438. data.
  439. Takes two required arguments: ``name`` which is the name of the file, and
  440. ``content`` which is an object containing the file's contents. The
  441. optional ``save`` argument controls whether or not the instance is
  442. saved after the file has been altered. Defaults to ``True``.
  443. Note that the ``content`` argument should be an instance of
  444. :class:`django.core.files.File`, not Python's built-in file object.
  445. You can construct a :class:`~django.core.files.File` from an existing
  446. Python file object like this::
  447. from django.core.files import File
  448. # Open an existing file using Python's built-in open()
  449. f = open('/tmp/hello.world')
  450. myfile = File(f)
  451. Or you can construct one from a Python string like this::
  452. from django.core.files.base import ContentFile
  453. myfile = ContentFile("hello world")
  454. For more information, see :doc:`/topics/files`.
  455. .. method:: FieldFile.delete(save=True)
  456. Deletes the file associated with this instance and clears all attributes on
  457. the field. Note: This method will close the file if it happens to be open when
  458. ``delete()`` is called.
  459. The optional ``save`` argument controls whether or not the instance is saved
  460. after the file has been deleted. Defaults to ``True``.
  461. ``FilePathField``
  462. -----------------
  463. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  464. A :class:`CharField` whose choices are limited to the filenames in a certain
  465. directory on the filesystem. Has three special arguments, of which the first is
  466. **required**:
  467. .. attribute:: FilePathField.path
  468. Required. The absolute filesystem path to a directory from which this
  469. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  470. .. attribute:: FilePathField.match
  471. Optional. A regular expression, as a string, that :class:`FilePathField`
  472. will use to filter filenames. Note that the regex will be applied to the
  473. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  474. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.
  475. .. attribute:: FilePathField.recursive
  476. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  477. whether all subdirectories of :attr:`~FilePathField.path` should be included
  478. .. attribute:: FilePathField.allow_files
  479. .. versionadded:: 1.5
  480. Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
  481. whether files in the specified location should be included. Either this or
  482. :attr:`~FilePathField.allow_folders` must be ``True``.
  483. .. attribute:: FilePathField.allow_folders
  484. .. versionadded:: 1.5
  485. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  486. whether folders in the specified location should be included. Either this
  487. or :attr:`~FilePathField.allow_files` must be ``True``.
  488. Of course, these arguments can be used together.
  489. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  490. base filename, not the full path. So, this example::
  491. FilePathField(path="/home/images", match="foo.*", recursive=True)
  492. ...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``
  493. because the :attr:`~FilePathField.match` applies to the base filename
  494. (``foo.png`` and ``bar.png``).
  495. By default, :class:`FilePathField` instances are
  496. created as ``varchar(100)`` columns in your database. As with other fields, you
  497. can change the maximum length using the :attr:`~CharField.max_length` argument.
  498. ``FloatField``
  499. --------------
  500. .. class:: FloatField([**options])
  501. A floating-point number represented in Python by a ``float`` instance.
  502. The admin represents this as an ``<input type="text">`` (a single-line input).
  503. .. _floatfield_vs_decimalfield:
  504. .. admonition:: ``FloatField`` vs. ``DecimalField``
  505. The :class:`FloatField` class is sometimes mixed up with the
  506. :class:`DecimalField` class. Although they both represent real numbers, they
  507. represent those numbers differently. ``FloatField`` uses Python's ``float``
  508. type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
  509. information on the difference between the two, see Python's documentation
  510. for the :mod:`decimal` module.
  511. ``ImageField``
  512. --------------
  513. .. class:: ImageField(upload_to=None, [height_field=None, width_field=None, max_length=100, **options])
  514. Inherits all attributes and methods from :class:`FileField`, but also
  515. validates that the uploaded object is a valid image.
  516. In addition to the special attributes that are available for :class:`FileField`,
  517. an :class:`ImageField` also has :attr:`~django.core.files.File.height` and
  518. :attr:`~django.core.files.File.width` attributes.
  519. To facilitate querying on those attributes, :class:`ImageField` has two extra
  520. optional arguments:
  521. .. attribute:: ImageField.height_field
  522. Name of a model field which will be auto-populated with the height of the
  523. image each time the model instance is saved.
  524. .. attribute:: ImageField.width_field
  525. Name of a model field which will be auto-populated with the width of the
  526. image each time the model instance is saved.
  527. Requires the `Python Imaging Library`_.
  528. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  529. By default, :class:`ImageField` instances are created as ``varchar(100)``
  530. columns in your database. As with other fields, you can change the maximum
  531. length using the :attr:`~CharField.max_length` argument.
  532. ``IntegerField``
  533. ----------------
  534. .. class:: IntegerField([**options])
  535. An integer. The admin represents this as an ``<input type="text">`` (a
  536. single-line input).
  537. ``IPAddressField``
  538. ------------------
  539. .. class:: IPAddressField([**options])
  540. An IP address, in string format (e.g. "192.0.2.30"). The admin represents this
  541. as an ``<input type="text">`` (a single-line input).
  542. ``GenericIPAddressField``
  543. -------------------------
  544. .. class:: GenericIPAddressField([protocol=both, unpack_ipv4=False, **options])
  545. .. versionadded:: 1.4
  546. An IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or
  547. ``2a02:42fe::4``). The admin represents this as an ``<input type="text">``
  548. (a single-line input).
  549. The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
  550. including using the IPv4 format suggested in paragraph 3 of that section, like
  551. ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
  552. ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
  553. are converted to lowercase.
  554. .. attribute:: GenericIPAddressField.protocol
  555. Limits valid inputs to the specified protocol.
  556. Accepted values are ``'both'`` (default), ``'IPv4'``
  557. or ``'IPv6'``. Matching is case insensitive.
  558. .. attribute:: GenericIPAddressField.unpack_ipv4
  559. Unpacks IPv4 mapped addresses like ``::ffff::192.0.2.1``.
  560. If this option is enabled that address would be unpacked to
  561. ``192.0.2.1``. Default is disabled. Can only be used
  562. when ``protocol`` is set to ``'both'``.
  563. ``NullBooleanField``
  564. --------------------
  565. .. class:: NullBooleanField([**options])
  566. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  567. this instead of a :class:`BooleanField` with ``null=True``. The admin represents
  568. this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
  569. ``PositiveIntegerField``
  570. ------------------------
  571. .. class:: PositiveIntegerField([**options])
  572. Like an :class:`IntegerField`, but must be either positive or zero (`0`).
  573. The value `0` is accepted for backward compatibility reasons.
  574. ``PositiveSmallIntegerField``
  575. -----------------------------
  576. .. class:: PositiveSmallIntegerField([**options])
  577. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  578. (database-dependent) point.
  579. ``SlugField``
  580. -------------
  581. .. class:: SlugField([max_length=50, **options])
  582. :term:`Slug` is a newspaper term. A slug is a short label for something,
  583. containing only letters, numbers, underscores or hyphens. They're generally used
  584. in URLs.
  585. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
  586. about database portability and :attr:`~CharField.max_length` in that section,
  587. too). If :attr:`~CharField.max_length` is not specified, Django will use a
  588. default length of 50.
  589. Implies setting :attr:`Field.db_index` to ``True``.
  590. It is often useful to automatically prepopulate a SlugField based on the value
  591. of some other value. You can do this automatically in the admin using
  592. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
  593. ``SmallIntegerField``
  594. ---------------------
  595. .. class:: SmallIntegerField([**options])
  596. Like an :class:`IntegerField`, but only allows values under a certain
  597. (database-dependent) point.
  598. ``TextField``
  599. -------------
  600. .. class:: TextField([**options])
  601. A large text field. The admin represents this as a ``<textarea>`` (a multi-line
  602. input).
  603. .. admonition:: MySQL users
  604. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  605. collation (which is *not* the default), there are some issues to be aware
  606. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  607. details.
  608. ``TimeField``
  609. -------------
  610. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  611. A time, represented in Python by a ``datetime.time`` instance. Accepts the same
  612. auto-population options as :class:`DateField`.
  613. The admin represents this as an ``<input type="text">`` with some JavaScript
  614. shortcuts.
  615. ``URLField``
  616. ------------
  617. .. class:: URLField([max_length=200, **options])
  618. A :class:`CharField` for a URL.
  619. The admin represents this as an ``<input type="text">`` (a single-line input).
  620. Like all :class:`CharField` subclasses, :class:`URLField` takes the optional
  621. :attr:`~CharField.max_length`argument. If you don't specify
  622. :attr:`~CharField.max_length`, a default of 200 is used.
  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.