fields.txt 45 KB

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