fields.txt 41 KB

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