fields.txt 46 KB

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