fields.txt 42 KB

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