fields.txt 43 KB

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