fields.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. .. _ref-models-fields:
  2. =====================
  3. Model field reference
  4. =====================
  5. .. module:: django.db.models.fields
  6. :synopsis: Built-in field types.
  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 easily :ref:`write your
  11. own custom model fields <howto-custom-model-fields>`.
  12. .. note::
  13. Technically, these models are defined in :mod:`django.db.models.fields`, but
  14. for convenience they're imported into :mod:`django.db.models`; the standard
  15. convention is to use ``from django.db import models`` and refer to fields as
  16. ``models.<Foo>Field``.
  17. .. _common-model-field-options:
  18. Field options
  19. =============
  20. The following arguments are available to all field types. All are optional.
  21. ``null``
  22. --------
  23. .. attribute:: Field.null
  24. If ``True``, Django will store empty values as ``NULL`` in the database. Default
  25. is ``False``.
  26. Note that empty string values will always get stored as empty strings, not as
  27. ``NULL``. Only use ``null=True`` for non-string fields such as integers,
  28. booleans and dates. For both types of fields, you will also need to set
  29. ``blank=True`` if you wish to permit empty values in forms, as the
  30. :attr:`~Field.null` parameter only affects database storage (see
  31. :attr:`~Field.blank`).
  32. Avoid using :attr:`~Field.null` on string-based fields such as
  33. :class:`CharField` and :class:`TextField` unless you have an excellent reason.
  34. If a string-based field has ``null=True``, that means it has two possible values
  35. for "no data": ``NULL``, and the empty string. In most cases, it's redundant to
  36. have two possible values for "no data;" Django convention is to use the empty
  37. string, not ``NULL``.
  38. .. note::
  39. When using the Oracle database backend, the ``null=True`` option will be
  40. coerced for string-based fields that can blank, and the value ``NULL`` will
  41. be stored to denote the empty string.
  42. ``blank``
  43. ---------
  44. .. attribute:: Field.blank
  45. If ``True``, the field is allowed to be blank. Default is ``False``.
  46. Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
  47. purely database-related, whereas :attr:`~Field.blank` is validation-related. If
  48. a field has ``blank=True``, validation on Django's admin site will allow entry
  49. of an empty value. If a field has ``blank=False``, the field will be required.
  50. ``choices``
  51. -----------
  52. .. attribute:: Field.choices
  53. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
  54. field.
  55. If this is given, Django's admin will use a select box instead of the standard
  56. text field and will limit choices to the choices given.
  57. A choices list looks like this::
  58. YEAR_IN_SCHOOL_CHOICES = (
  59. ('FR', 'Freshman'),
  60. ('SO', 'Sophomore'),
  61. ('JR', 'Junior'),
  62. ('SR', 'Senior'),
  63. ('GR', 'Graduate'),
  64. )
  65. The first element in each tuple is the actual value to be stored. The second
  66. element is the human-readable name for the option.
  67. The choices list can be defined either as part of your model class::
  68. class Foo(models.Model):
  69. GENDER_CHOICES = (
  70. ('M', 'Male'),
  71. ('F', 'Female'),
  72. )
  73. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  74. or outside your model class altogether::
  75. GENDER_CHOICES = (
  76. ('M', 'Male'),
  77. ('F', 'Female'),
  78. )
  79. class Foo(models.Model):
  80. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  81. You can also collect your available choices into named groups that can
  82. be used for organizational purposes::
  83. MEDIA_CHOICES = (
  84. ('Audio', (
  85. ('vinyl', 'Vinyl'),
  86. ('cd', 'CD'),
  87. )
  88. ),
  89. ('Video', (
  90. ('vhs', 'VHS Tape'),
  91. ('dvd', 'DVD'),
  92. )
  93. ),
  94. ('unknown', 'Unknown'),
  95. )
  96. The first element in each tuple is the name to apply to the group. The
  97. second element is an iterable of 2-tuples, with each 2-tuple containing
  98. a value and a human-readable name for an option. Grouped options may be
  99. combined with ungrouped options within a single list (such as the
  100. `unknown` option in this example).
  101. For each model field that has :attr:`~Field.choices` set, Django will add a
  102. method to retrieve the human-readable name for the field's current value. See
  103. :meth:`~django.db.models.Model.get_FOO_display` in the database API
  104. documentation.
  105. Finally, note that choices can be any iterable object -- not necessarily a list
  106. or tuple. This lets you construct choices dynamically. But if you find yourself
  107. hacking :attr:`~Field.choices` to be dynamic, you're probably better off using a
  108. proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is
  109. meant for static data that doesn't change much, if ever.
  110. ``db_column``
  111. -------------
  112. .. attribute:: Field.db_column
  113. The name of the database column to use for this field. If this isn't given,
  114. Django will use the field's name.
  115. If your database column name is an SQL reserved word, or contains
  116. characters that aren't allowed in Python variable names -- notably, the
  117. hyphen -- that's OK. Django quotes column and table names behind the
  118. scenes.
  119. ``db_index``
  120. ------------
  121. .. attribute:: Field.db_index
  122. If ``True``, djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a
  123. ``CREATE INDEX`` statement for this field.
  124. ``db_tablespace``
  125. -----------------
  126. .. attribute:: Field.db_tablespace
  127. .. versionadded:: 1.0
  128. The name of the database tablespace to use for this field's index, if this field
  129. is indexed. The default is the project's :setting:`DEFAULT_INDEX_TABLESPACE`
  130. setting, if set, or the :attr:`~Field.db_tablespace` of the model, if any. If
  131. the backend doesn't support tablespaces, this option is ignored.
  132. ``default``
  133. -----------
  134. .. attribute:: Field.default
  135. The default value for the field. This can be a value or a callable object. If
  136. callable it will be called every time a new object is created.
  137. ``editable``
  138. ------------
  139. .. attribute:: Field.editable
  140. If ``False``, the field will not be editable in the admin or via forms
  141. automatically generated from the model class. Default is ``True``.
  142. ``help_text``
  143. -------------
  144. .. attribute:: Field.help_text
  145. Extra "help" text to be displayed under the field on the object's admin form.
  146. It's useful for documentation even if your object doesn't have an admin form.
  147. Note that this value is *not* HTML-escaped when it's displayed in the admin
  148. interface. This lets you include HTML in :attr:`~Field.help_text` if you so
  149. desire. For example::
  150. help_text="Please use the following format: <em>YYYY-MM-DD</em>."
  151. Alternatively you can use plain text and
  152. ``django.utils.html.escape()`` to escape any HTML special characters.
  153. ``primary_key``
  154. ---------------
  155. .. attribute:: Field.primary_key
  156. If ``True``, this field is the primary key for the model.
  157. If you don't specify ``primary_key=True`` for any fields in your model, Django
  158. will automatically add an :class:`IntegerField` to hold the primary key, so you
  159. don't need to set ``primary_key=True`` on any of your fields unless you want to
  160. override the default primary-key behavior. For more, see
  161. :ref:`automatic-primary-key-fields`.
  162. ``primary_key=True`` implies :attr:`null=False <Field.null>` and :attr:`unique=True <Field.unique>`.
  163. Only one primary key is allowed on an object.
  164. ``unique``
  165. ----------
  166. .. attribute:: Field.unique
  167. If ``True``, this field must be unique throughout the table.
  168. This is enforced at the database level and at the Django admin-form level. If
  169. you try to save a model with a duplicate value in a :attr:`~Field.unique`
  170. field, a :exc:`django.db.IntegrityError` will be raised by the model's
  171. :meth:`~django.db.models.Model.save` method.
  172. This options is valid on all field types except :class:`ManyToManyField`.
  173. ``unique_for_date``
  174. -------------------
  175. .. attribute:: Field.unique_for_date
  176. Set this to the name of a :class:`DateField` or :class:`DateTimeField` to
  177. require that this field be unique for the value of the date field.
  178. For example, if you have a field ``title`` that has
  179. ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
  180. records with the same ``title`` and ``pub_date``.
  181. This is enforced at the Django admin-form level but not at the database level.
  182. ``unique_for_month``
  183. --------------------
  184. .. attribute:: Field.unique_for_month
  185. Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
  186. respect to the month.
  187. ``unique_for_year``
  188. -------------------
  189. .. attribute:: Field.unique_for_year
  190. Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
  191. .. _model-field-types:
  192. Field types
  193. ===========
  194. .. currentmodule:: django.db.models
  195. ``AutoField``
  196. -------------
  197. .. class:: AutoField(**options)
  198. An :class:`IntegerField` that automatically increments
  199. according to available IDs. You usually won't need to use this directly; a
  200. primary key field will automatically be added to your model if you don't specify
  201. otherwise. See :ref:`automatic-primary-key-fields`.
  202. ``BooleanField``
  203. ----------------
  204. .. class:: BooleanField(**options)
  205. A true/false field.
  206. The admin represents this as a checkbox.
  207. ``CharField``
  208. -------------
  209. .. class:: CharField(max_length=None, [**options])
  210. A string field, for small- to large-sized strings.
  211. For large amounts of text, use :class:`~django.db.models.TextField`.
  212. The admin represents this as an ``<input type="text">`` (a single-line input).
  213. :class:`CharField` has one extra required argument:
  214. .. attribute:: CharField.max_length
  215. The maximum length (in characters) of the field. The max_length is enforced
  216. at the database level and in Django's validation.
  217. .. admonition:: MySQL users
  218. If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin``
  219. collation (which is *not* the default), there are some issues to be aware
  220. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  221. details.
  222. ``CommaSeparatedIntegerField``
  223. ------------------------------
  224. .. class:: CommaSeparatedIntegerField(max_length=None, [**options])
  225. A field of integers separated by commas. As in :class:`CharField`, the
  226. :attr:`~CharField.max_length` argument is required.
  227. ``DateField``
  228. -------------
  229. .. class:: DateField([auto_now=False, auto_now_add=False, **options])
  230. A date field. Has a few extra optional arguments:
  231. .. attribute:: DateField.auto_now
  232. Automatically set the field to now every time the object is saved. Useful
  233. for "last-modified" timestamps. Note that the current date is *always* used;
  234. it's not just a default value that you can override.
  235. .. attribute:: DateField.auto_now_add
  236. Automatically set the field to now when the object is first created. Useful
  237. for creation of timestamps. Note that the current date is *always* used;
  238. it's not just a default value that you can override.
  239. The admin represents this as an ``<input type="text">`` with a JavaScript
  240. calendar, and a shortcut for "Today". The JavaScript calendar will always start
  241. the week on a Sunday.
  242. ``DateTimeField``
  243. -----------------
  244. .. class:: DateTimeField([auto_now=False, auto_now_add=False, **options])
  245. A date and time field. Takes the same extra options as :class:`DateField`.
  246. The admin represents this as two ``<input type="text">`` fields, with JavaScript
  247. shortcuts.
  248. ``DecimalField``
  249. ----------------
  250. .. versionadded:: 1.0
  251. .. class:: DecimalField(max_digits=None, decimal_places=None, [**options])
  252. A fixed-precision decimal number, represented in Python by a
  253. :class:`~decimal.Decimal` instance. Has two **required** arguments:
  254. .. attribute:: DecimalField.max_digits
  255. The maximum number of digits allowed in the number
  256. .. attribute:: DecimalField.decimal_places
  257. The number of decimal places to store with the number
  258. For example, to store numbers up to 999 with a resolution of 2 decimal places,
  259. you'd use::
  260. models.DecimalField(..., max_digits=5, decimal_places=2)
  261. And to store numbers up to approximately one billion with a resolution of 10
  262. decimal places::
  263. models.DecimalField(..., max_digits=19, decimal_places=10)
  264. The admin represents this as an ``<input type="text">`` (a single-line input).
  265. ``EmailField``
  266. --------------
  267. .. class:: EmailField([max_length=75, **options])
  268. A :class:`CharField` that checks that the value is a valid e-mail address.
  269. In Django 0.96, this doesn't accept :attr:`~CharField.max_length`; its
  270. :class:`~CharField.max_length` is automatically set to 75. In the Django
  271. development version, :class:`~CharField.max_length` is set to 75 by default, but
  272. you can specify it to override default behavior.
  273. ``FileField``
  274. -------------
  275. .. class:: FileField(upload_to=None, [max_length=100, **options])
  276. A file-upload field. Has one **required** argument:
  277. .. attribute:: FileField.upload_to
  278. A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
  279. setting to determine the value of the :attr:`~django.core.files.File.url`
  280. attribute.
  281. This path may contain `strftime formatting`_, which will be replaced by the
  282. date/time of the file upload (so that uploaded files don't fill up the given
  283. directory).
  284. .. versionchanged:: 1.0
  285. This may also be a callable, such as a function, which will be called to
  286. obtain the upload path, including the filename. This callable must be able
  287. to accept two arguments, and return a Unix-style path (with forward slashes)
  288. to be passed along to the storage system. The two arguments that will be
  289. passed are:
  290. ====================== ===============================================
  291. Argument Description
  292. ====================== ===============================================
  293. ``instance`` An instance of the model where the
  294. ``FileField`` is defined. More specifically,
  295. this is the particular instance where the
  296. current file is being attached.
  297. In most cases, this object will not have been
  298. saved to the database yet, so if it uses the
  299. default ``AutoField``, *it might not yet have a
  300. value for its primary key field*.
  301. ``filename`` The filename that was originally given to the
  302. file. This may or may not be taken into account
  303. when determining the final destination path.
  304. ====================== ===============================================
  305. Also has one optional argument:
  306. .. attribute:: FileField.storage
  307. .. versionadded:: 1.0
  308. Optional. A storage object, which handles the storage and retrieval of your
  309. files. See :ref:`topics-files` for details on how to provide this object.
  310. The admin represents this field as an ``<input type="file">`` (a file-upload
  311. widget).
  312. Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
  313. takes a few steps:
  314. 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the
  315. full path to a directory where you'd like Django to store uploaded files.
  316. (For performance, these files are not stored in the database.) Define
  317. :setting:`MEDIA_URL` as the base public URL of that directory. Make sure
  318. that this directory is writable by the Web server's user account.
  319. 2. Add the :class:`FileField` or :class:`ImageField` to your model, making
  320. sure to define the :attr:`~FileField.upload_to` option to tell Django
  321. to which subdirectory of :setting:`MEDIA_ROOT` it should upload files.
  322. 3. All that will be stored in your database is a path to the file
  323. (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
  324. convenience :attr:`~django.core.files.File.url` function provided by
  325. Django. For example, if your :class:`ImageField` is called ``mug_shot``,
  326. you can get the absolute URL to your image in a template with
  327. ``{{ object.mug_shot.url }}``.
  328. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
  329. :attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
  330. part of :attr:`~FileField.upload_to` is `strftime formatting`_; ``'%Y'`` is the
  331. four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is the two-digit
  332. day. If you upload a file on Jan. 15, 2007, it will be saved in the directory
  333. ``/home/media/photos/2007/01/15``.
  334. If you want to retrieve the upload file's on-disk filename, or a URL that refers
  335. to that file, or the file's size, you can use the
  336. :attr:`~django.core.files.File.name`, :attr:`~django.core.files.File.url`
  337. and :attr:`~django.core.files.File.size` attributes; see :ref:`topics-files`.
  338. Note that whenever you deal with uploaded files, you should pay close attention
  339. to where you're uploading them and what type of files they are, to avoid
  340. security holes. *Validate all uploaded files* so that you're sure the files are
  341. what you think they are. For example, if you blindly let somebody upload files,
  342. without validation, to a directory that's within your Web server's document
  343. root, then somebody could upload a CGI or PHP script and execute that script by
  344. visiting its URL on your site. Don't allow that.
  345. .. versionadded:: 1.0
  346. The ``max_length`` argument was added in this version.
  347. By default, :class:`FileField` instances are
  348. created as ``varchar(100)`` columns in your database. As with other fields, you
  349. can change the maximum length using the :attr:`~CharField.max_length` argument.
  350. .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
  351. ``FilePathField``
  352. -----------------
  353. .. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options])
  354. A :class:`CharField` whose choices are limited to the filenames in a certain
  355. directory on the filesystem. Has three special arguments, of which the first is
  356. **required**:
  357. .. attribute:: FilePathField.path
  358. Required. The absolute filesystem path to a directory from which this
  359. :class:`FilePathField` should get its choices. Example: ``"/home/images"``.
  360. .. attribute:: FilePathField.match
  361. Optional. A regular expression, as a string, that :class:`FilePathField`
  362. will use to filter filenames. Note that the regex will be applied to the
  363. base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
  364. match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
  365. .. attribute:: FilePathField.recursive
  366. Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
  367. whether all subdirectories of :attr:`~FilePathField.path` should be included
  368. Of course, these arguments can be used together.
  369. The one potential gotcha is that :attr:`~FilePathField.match` applies to the
  370. base filename, not the full path. So, this example::
  371. FilePathField(path="/home/images", match="foo.*", recursive=True)
  372. ...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
  373. because the :attr:`~FilePathField.match` applies to the base filename
  374. (``foo.gif`` and ``bar.gif``).
  375. .. versionadded:: 1.0
  376. The ``max_length`` argument was added in this version.
  377. By default, :class:`FilePathField` instances are
  378. created as ``varchar(100)`` columns in your database. As with other fields, you
  379. can change the maximum length using the :attr:`~CharField.max_length` argument.
  380. ``FloatField``
  381. --------------
  382. .. class:: FloatField([**options])
  383. **Changed in Django development version**
  384. A floating-point number represented in Python by a ``float`` instance.
  385. The admin represents this as an ``<input type="text">`` (a single-line input).
  386. **NOTE:** The semantics of :class:`FloatField` have changed in the Django
  387. development version. See the `Django 0.96 documentation`_ for the old behavior.
  388. .. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield
  389. ``ImageField``
  390. --------------
  391. .. class:: ImageField(upload_to-None, [height_field=None, width_field=None, max_length=100, **options])
  392. Like :class:`FileField`, but validates that the uploaded object is a valid
  393. image. Has two extra optional arguments:
  394. .. attribute:: ImageField.height_field
  395. Name of a model field which will be auto-populated with the height of the
  396. image each time the model instance is saved.
  397. .. attribute:: ImageField.width_field
  398. Name of a model field which will be auto-populated with the width of the
  399. image each time the model instance is saved.
  400. In addition to the special attributes that are available for :class:`FileField`,
  401. an :class:`ImageField` also has ``File.height`` and ``File.width`` attributes.
  402. See :ref:`topics-files`.
  403. Requires the `Python Imaging Library`_.
  404. .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  405. .. versionadded:: 1.0
  406. The ``max_length`` argument was added in this version.
  407. By default, :class:`ImageField` instances are
  408. created as ``varchar(100)`` columns in your database. As with other fields, you
  409. can change the maximum length using the :attr:`~CharField.max_length` argument.
  410. ``IntegerField``
  411. ----------------
  412. .. class:: IntegerField([**options])
  413. An integer. The admin represents this as an ``<input type="text">`` (a
  414. single-line input).
  415. ``IPAddressField``
  416. ------------------
  417. .. class:: IPAddressField([**options])
  418. An IP address, in string format (e.g. "192.0.2.30"). The admin represents this
  419. as an ``<input type="text">`` (a single-line input).
  420. ``NullBooleanField``
  421. --------------------
  422. .. class:: NullBooleanField([**options])
  423. Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use
  424. this instead of a :class:`BooleanField` with ``null=True``. The admin represents
  425. this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
  426. ``PositiveIntegerField``
  427. ------------------------
  428. .. class:: PositiveIntegerField([**options])
  429. Like an :class:`IntegerField`, but must be positive.
  430. ``PositiveSmallIntegerField``
  431. -----------------------------
  432. .. class:: PositiveIntegerField([**options])
  433. Like a :class:`PositiveIntegerField`, but only allows values under a certain
  434. (database-dependent) point.
  435. ``SlugField``
  436. -------------
  437. .. class:: SlugField([max_length=50, **options])
  438. :term:`Slug` is a newspaper term. A slug is a short label for something,
  439. containing only letters, numbers, underscores or hyphens. They're generally used
  440. in URLs.
  441. Like a CharField, you can specify :attr:`~CharField.max_length`. If
  442. :attr:`~CharField.max_length` is not specified, Django will use a default length
  443. of 50.
  444. Implies setting :attr:`Field.db_index` to ``True``.
  445. ``SmallIntegerField``
  446. ---------------------
  447. .. class:: SmallIntegerField([**options])
  448. Like an :class:`IntegerField`, but only allows values under a certain
  449. (database-dependent) point.
  450. ``TextField``
  451. -------------
  452. .. class:: TextField([**options])
  453. A large text field. The admin represents this as a ``<textarea>`` (a multi-line
  454. input).
  455. .. admonition:: MySQL users
  456. If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin``
  457. collation (which is *not* the default), there are some issues to be aware
  458. of. Refer to the :ref:`MySQL database notes <mysql-collation>` for
  459. details.
  460. ``TimeField``
  461. -------------
  462. .. class:: TimeField([auto_now=False, auto_now_add=False, **options])
  463. A time. Accepts the same auto-population options as :class:`DateField` and
  464. :class:`DateTimeField`. The admin represents this as an ``<input type="text">``
  465. with some JavaScript shortcuts.
  466. ``URLField``
  467. ------------
  468. .. class:: URLField([verify_exists=True, max_length=200, **options])
  469. A :class:`CharField` for a URL. Has one extra optional argument:
  470. .. attribute:: URLField.verify_exists
  471. If ``True`` (the default), the URL given will be checked for existence
  472. (i.e., the URL actually loads and doesn't give a 404 response).
  473. The admin represents this as an ``<input type="text">`` (a single-line input).
  474. Like all ::class:`CharField` subclasses, :class:`URLField` takes the optional
  475. :attr:`~CharField.max_length`argument. If you don't specify
  476. :attr:`~CharField.max_length`, a default of 200 is used.
  477. ``XMLField``
  478. ------------
  479. .. class:: XMLField(schema_path=None, [**options])
  480. A :class:`TextField` that checks that the value is valid XML that matches a
  481. given schema. Takes one required argument:
  482. .. attribute:: schema_path
  483. The filesystem path to a RelaxNG_ schema against which to validate the
  484. field.
  485. .. _RelaxNG: http://www.relaxng.org/
  486. Relationship fields
  487. ===================
  488. .. module:: django.db.models.fields.related
  489. :synopsis: Related field types
  490. .. currentmodule:: django.db.models
  491. Django also defines a set of fields that represent relations.
  492. .. _ref-foreignkey:
  493. ``ForeignKey``
  494. --------------
  495. .. class:: ForeignKey(othermodel, [**options])
  496. A many-to-one relationship. Requires a positional argument: the class to which
  497. the model is related.
  498. .. _recursive-relationships:
  499. To create a recursive relationship -- an object that has a many-to-one
  500. relationship with itself -- use ``models.ForeignKey('self')``.
  501. .. _lazy-relationships:
  502. If you need to create a relationship on a model that has not yet been defined,
  503. you can use the name of the model, rather than the model object itself::
  504. class Car(models.Model):
  505. manufacturer = models.ForeignKey('Manufacturer')
  506. # ...
  507. class Manufacturer(models.Model):
  508. # ...
  509. Note, however, that this only refers to models in the same ``models.py`` file --
  510. you cannot use a string to reference a model defined in another application or
  511. imported from elsewhere.
  512. .. versionchanged:: 1.0
  513. Refering models in other applications must include the application label.
  514. To refer to models defined in another
  515. application, you must instead explicitly specify the application label. For
  516. example, if the ``Manufacturer`` model above is defined in another application
  517. called ``production``, you'd need to use::
  518. class Car(models.Model):
  519. manufacturer = models.ForeignKey('production.Manufacturer')
  520. Behind the scenes, Django appends ``"_id"`` to the field name to create its
  521. database column name. In the above example, the database table for the ``Car``
  522. model will have a ``manufacturer_id`` column. (You can change this explicitly by
  523. specifying :attr:`~Field.db_column`) However, your code should never have to
  524. deal with the database column name, unless you write custom SQL. You'll always
  525. deal with the field names of your model object.
  526. .. _foreign-key-arguments:
  527. :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that
  528. define the details of how the relation works.
  529. .. attribute:: ForeignKey.limit_choices_to
  530. A dictionary of lookup arguments and values (see :ref:`topics-db-queries`)
  531. that limit the available admin choices for this object. Use this with
  532. functions from the Python ``datetime`` module to limit choices of objects by
  533. date. For example::
  534. limit_choices_to = {'pub_date__lte': datetime.now}
  535. only allows the choice of related objects with a ``pub_date`` before the
  536. current date/time to be chosen.
  537. Instead of a dictionary this can also be a :class:`~django.db.models.Q`
  538. object (an object with a :meth:`get_sql` method) for more complex queries.
  539. ``limit_choices_to`` has no effect on the inline FormSets that are created
  540. to display related objects in the admin.
  541. .. attribute:: ForeignKey.related_name
  542. The name to use for the relation from the related object back to this one.
  543. See the :ref:`related objects documentation <backwards-related-objects>` for
  544. a full explanation and example. Note that you must set this value
  545. when defining relations on :ref:`abstract models
  546. <abstract-base-classes>`; and when you do so
  547. :ref:`some special syntax <abstract-related-name>` is available.
  548. .. attribute:: ForeignKey.to_field
  549. The field on the related object that the relation is to. By default, Django
  550. uses the primary key of the related object.
  551. .. _ref-manytomany:
  552. ``ManyToManyField``
  553. -------------------
  554. .. class:: ManyToManyField(othermodel, [**options])
  555. A many-to-many relationship. Requires a positional argument: the class to which
  556. the model is related. This works exactly the same as it does for
  557. :class:`ForeignKey`, including all the options regarding :ref:`recursive
  558. <recursive-relationships>` and :ref:`lazy <lazy-relationships>` relationships.
  559. Behind the scenes, Django creates an intermediary join table to represent the
  560. many-to-many relationship. By default, this table name is generated using the
  561. names of the two tables being joined. Since some databases don't support table
  562. names above a certain length (often 32 characters), these table names will be
  563. automatically truncated to 32 characters and a uniqueness hash will be used.
  564. This means you might see table names like ``author_books_9cdf4``; this is
  565. perfectly normal. You can manually provide the name of the join table using
  566. the :attr:`~ManyToManyField.db_table` option.
  567. .. _manytomany-arguments:
  568. :class:`ManyToManyField` accepts an extra set of arguments -- all optional --
  569. that control how the relationship functions.
  570. .. attribute:: ManyToManyField.related_name
  571. Same as :attr:`ForeignKey.related_name`.
  572. .. attribute:: ManyToManyFields.limit_choices_to
  573. Same as :attr:`ForeignKey.limit_choices_to`.
  574. ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with
  575. an intermediate table.
  576. .. attribute:: ManyToManyFields.symmetrical
  577. Only used in the definition of ManyToManyFields on self. Consider the
  578. following model::
  579. class Person(models.Model):
  580. friends = models.ManyToManyField("self")
  581. When Django processes this model, it identifies that it has a
  582. :class:`ManyToManyField` on itself, and as a result, it doesn't add a
  583. ``person_set`` attribute to the ``Person`` class. Instead, the
  584. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
  585. your friend, then you are my friend.
  586. If you do not want symmetry in many-to-many relationships with ``self``, set
  587. :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
  588. add the descriptor for the reverse relationship, allowing
  589. :class:`ManyToManyField` relationships to be non-symmetrical.
  590. .. attribute:: ManyToManyField.db_table
  591. The name of the table to create for storing the many-to-many data. If this
  592. is not provided, Django will assume a default name based upon the names of
  593. the two tables being joined.
  594. .. _ref-onetoone:
  595. ``OneToOneField``
  596. -----------------
  597. .. class:: OneToOneField(othermodel, [parent_link=False, **options])
  598. A one-to-one relationship. Conceptually, this is similar to a
  599. :class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the
  600. "reverse" side of the relation will directly return a single object.
  601. This is most useful as the primary key of a model which "extends"
  602. another model in some way; :ref:`multi-table-inheritance` is
  603. implemented by adding an implicit one-to-one relation from the child
  604. model to the parent model, for example.
  605. One positional argument is required: the class to which the model will be
  606. related. This works exactly the same as it does for :class:`ForeignKey`,
  607. including all the options regarding :ref:`recursive <recursive-relationships>`
  608. and :ref:`lazy <lazy-relationships>` relationships.
  609. .. _onetoone-arguments:
  610. Additionally, ``OneToOneField`` accepts all of the extra arguments
  611. accepted by :class:`ForeignKey`, plus one extra argument:
  612. .. attribute:: OneToOneField.parent_link
  613. When ``True`` and used in a model which inherits from another
  614. (concrete) model, indicates that this field should be used as the
  615. link back to the parent class, rather than the extra
  616. ``OneToOneField`` which would normally be implicitly created by
  617. subclassing.