fields.txt 34 KB

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