databases.txt 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. .. _ref-databases:
  2. =========
  3. Databases
  4. =========
  5. Django attempts to support as many features as possible on all database
  6. backends. However, not all database backends are alike, and we've had to make
  7. design decisions on which features to support and which assumptions we can make
  8. safely.
  9. This file describes some of the features that might be relevant to Django
  10. usage. Of course, it is not intended as a replacement for server-specific
  11. documentation or reference manuals.
  12. .. _postgresql-notes:
  13. PostgreSQL notes
  14. ================
  15. PostgreSQL 8.2 to 8.2.4
  16. -----------------------
  17. The implementation of the population statistics aggregates ``STDDEV_POP`` and
  18. ``VAR_POP`` that shipped with PostgreSQL 8.2 to 8.2.4 are `known to be
  19. faulty`_. Users of these releases of PostgreSQL are advised to upgrade to
  20. `Release 8.2.5`_ or later. Django will raise a ``NotImplementedError`` if you
  21. attempt to use the ``StdDev(sample=False)`` or ``Variance(sample=False)``
  22. aggregate with a database backend that falls within the affected release range.
  23. .. _known to be faulty: http://archives.postgresql.org/pgsql-bugs/2007-07/msg00046.php
  24. .. _Release 8.2.5: http://developer.postgresql.org/pgdocs/postgres/release-8-2-5.html
  25. Transaction handling
  26. ---------------------
  27. :ref:`By default <topics-db-transactions>`, Django starts a transaction when a
  28. database connection is first used and commits the result at the end of the
  29. request/response handling. The PostgreSQL backends normally operate the same
  30. as any other Django backend in this respect.
  31. Autocommit mode
  32. ~~~~~~~~~~~~~~~
  33. .. versionadded:: 1.1
  34. If your application is particularly read-heavy and doesn't make many
  35. database writes, the overhead of a constantly open transaction can
  36. sometimes be noticeable. For those situations, if you're using the
  37. ``postgresql_psycopg2`` backend, you can configure Django to use
  38. *"autocommit"* behavior for the connection, meaning that each database
  39. operation will normally be in its own transaction, rather than having
  40. the transaction extend over multiple operations. In this case, you can
  41. still manually start a transaction if you're doing something that
  42. requires consistency across multiple database operations. The
  43. autocommit behavior is enabled by setting the ``autocommit`` key in
  44. the :setting:`OPTIONS` part of your database configuration in
  45. :setting:`DATABASES`::
  46. OPTIONS = {
  47. "autocommit": True,
  48. }
  49. In this configuration, Django still ensures that :ref:`delete()
  50. <topics-db-queries-delete>` and :ref:`update() <topics-db-queries-update>`
  51. queries run inside a single transaction, so that either all the affected
  52. objects are changed or none of them are.
  53. .. admonition:: This is database-level autocommit
  54. This functionality is not the same as the
  55. :ref:`topics-db-transactions-autocommit` decorator. That decorator
  56. is a Django-level implementation that commits automatically after
  57. data changing operations. The feature enabled using the
  58. :setting:`OPTIONS` option provides autocommit behavior at the
  59. database adapter level. It commits after *every* operation.
  60. If you are using this feature and performing an operation akin to delete or
  61. updating that requires multiple operations, you are strongly recommended to
  62. wrap you operations in manual transaction handling to ensure data consistency.
  63. You should also audit your existing code for any instances of this behavior
  64. before enabling this feature. It's faster, but it provides less automatic
  65. protection for multi-call operations.
  66. Indexes for ``varchar`` and ``text`` columns
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  68. .. versionadded:: 1.1.2
  69. When specifying ``db_index=True`` on your model fields, Django typically
  70. outputs a single ``CREATE INDEX`` statement. However, if the database type
  71. for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
  72. ``FileField``, and ``TextField``), then Django will create
  73. an additional index that uses an appropriate `PostgreSQL operator class`_
  74. for the column. The extra index is necessary to correctly perfrom
  75. lookups that use the ``LIKE`` operator in their SQL, as is done with the
  76. ``contains`` and ``startswith`` lookup types.
  77. .. _PostgreSQL operator class: http://www.postgresql.org/docs/8.4/static/indexes-opclass.html
  78. .. _mysql-notes:
  79. MySQL notes
  80. ===========
  81. Django expects the database to support transactions, referential integrity, and
  82. Unicode (UTF-8 encoding). Fortunately, MySQL_ has all these features as
  83. available as far back as 3.23. While it may be possible to use 3.23 or 4.0,
  84. you'll probably have less trouble if you use 4.1 or 5.0.
  85. MySQL 4.1
  86. ---------
  87. `MySQL 4.1`_ has greatly improved support for character sets. It is possible to
  88. set different default character sets on the database, table, and column.
  89. Previous versions have only a server-wide character set setting. It's also the
  90. first version where the character set can be changed on the fly. 4.1 also has
  91. support for views, but Django currently doesn't use views.
  92. MySQL 5.0
  93. ---------
  94. `MySQL 5.0`_ adds the ``information_schema`` database, which contains detailed
  95. data on all database schema. Django's ``inspectdb`` feature uses this
  96. ``information_schema`` if it's available. 5.0 also has support for stored
  97. procedures, but Django currently doesn't use stored procedures.
  98. .. _MySQL: http://www.mysql.com/
  99. .. _MySQL 4.1: http://dev.mysql.com/doc/refman/4.1/en/index.html
  100. .. _MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/index.html
  101. Storage engines
  102. ---------------
  103. MySQL has several `storage engines`_ (previously called table types). You can
  104. change the default storage engine in the server configuration.
  105. The default engine is MyISAM_ [#]_. The main drawback of MyISAM is that it
  106. doesn't currently support transactions or foreign keys. On the plus side, it's
  107. currently the only engine that supports full-text indexing and searching.
  108. The InnoDB_ engine is fully transactional and supports foreign key references.
  109. The BDB_ engine, like InnoDB, is also fully transactional and supports foreign
  110. key references. However, its use seems to be deprecated.
  111. `Other storage engines`_, including SolidDB_ and Falcon_, are on the horizon.
  112. For now, InnoDB is probably your best choice.
  113. .. _storage engines: http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html
  114. .. _MyISAM: http://dev.mysql.com/doc/refman/5.0/en/myisam-storage-engine.html
  115. .. _BDB: http://dev.mysql.com/doc/refman/5.0/en/bdb-storage-engine.html
  116. .. _InnoDB: http://dev.mysql.com/doc/refman/5.0/en/innodb.html
  117. .. _Other storage engines: http://dev.mysql.com/doc/refman/5.1/en/storage-engines-other.html
  118. .. _SolidDB: http://forge.mysql.com/projects/project.php?id=139
  119. .. _Falcon: http://dev.mysql.com/doc/falcon/en/index.html
  120. .. [#] Unless this was changed by the packager of your MySQL package. We've
  121. had reports that the Windows Community Server installer sets up InnoDB as
  122. the default storage engine, for example.
  123. MySQLdb
  124. -------
  125. `MySQLdb`_ is the Python interface to MySQL. Version 1.2.1p2 or later is
  126. required for full MySQL support in Django.
  127. .. note::
  128. If you see ``ImportError: cannot import name ImmutableSet`` when trying to
  129. use Django, your MySQLdb installation may contain an outdated ``sets.py``
  130. file that conflicts with the built-in module of the same name from Python
  131. 2.4 and later. To fix this, verify that you have installed MySQLdb version
  132. 1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
  133. directory that was left by an earlier version.
  134. .. _MySQLdb: http://sourceforge.net/projects/mysql-python
  135. Creating your database
  136. ----------------------
  137. You can `create your database`_ using the command-line tools and this SQL::
  138. CREATE DATABASE <dbname> CHARACTER SET utf8;
  139. This ensures all tables and columns will use UTF-8 by default.
  140. .. _create your database: http://dev.mysql.com/doc/refman/5.0/en/create-database.html
  141. .. _mysql-collation:
  142. Collation settings
  143. ~~~~~~~~~~~~~~~~~~
  144. The collation setting for a column controls the order in which data is sorted
  145. as well as what strings compare as equal. It can be set on a database-wide
  146. level and also per-table and per-column. This is `documented thoroughly`_ in
  147. the MySQL documentation. In all cases, you set the collation by directly
  148. manipulating the database tables; Django doesn't provide a way to set this on
  149. the model definition.
  150. .. _documented thoroughly: http://dev.mysql.com/doc/refman/5.0/en/charset.html
  151. By default, with a UTF-8 database, MySQL will use the
  152. ``utf8_general_ci_swedish`` collation. This results in all string equality
  153. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
  154. ``"freD"`` are considered equal at the database level. If you have a unique
  155. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
  156. ``"AA"`` into the same column, since they compare as equal (and, hence,
  157. non-unique) with the default collation.
  158. In many cases, this default will not be a problem. However, if you really want
  159. case-sensitive comparisons on a particular column or table, you would change
  160. the column or table to use the ``utf8_bin`` collation. The main thing to be
  161. aware of in this case is that if you are using MySQLdb 1.2.2, the database backend in Django will then return
  162. bytestrings (instead of unicode strings) for any character fields it returns
  163. receive from the database. This is a strong variation from Django's normal
  164. practice of *always* returning unicode strings. It is up to you, the
  165. developer, to handle the fact that you will receive bytestrings if you
  166. configure your table(s) to use ``utf8_bin`` collation. Django itself should work
  167. smoothly with such columns, but if your code must be prepared to call
  168. ``django.utils.encoding.smart_unicode()`` at times if it really wants to work
  169. with consistent data -- Django will not do this for you (the database backend
  170. layer and the model population layer are separated internally so the database
  171. layer doesn't know it needs to make this conversion in this one particular
  172. case).
  173. If you're using MySQLdb 1.2.1p2, Django's standard
  174. :class:`~django.db.models.CharField` class will return unicode strings even
  175. with ``utf8_bin`` collation. However, :class:`~django.db.models.TextField`
  176. fields will be returned as an ``array.array`` instance (from Python's standard
  177. ``array`` module). There isn't a lot Django can do about that, since, again,
  178. the information needed to make the necessary conversions isn't available when
  179. the data is read in from the database. This problem was `fixed in MySQLdb
  180. 1.2.2`_, so if you want to use :class:`~django.db.models.TextField` with
  181. ``utf8_bin`` collation, upgrading to version 1.2.2 and then dealing with the
  182. bytestrings (which shouldn't be too difficult) is the recommended solution.
  183. Should you decide to use ``utf8_bin`` collation for some of your tables with
  184. MySQLdb 1.2.1p2, you should still use ``utf8_collation_ci_swedish`` (the
  185. default) collation for the :class:`django.contrib.sessions.models.Session`
  186. table (usually called ``django_session``) and the
  187. :class:`django.contrib.admin.models.LogEntry` table (usually called
  188. ``django_admin_log``). Those are the two standard tables that use
  189. :class:`~django.db.model.TextField` internally.
  190. .. _fixed in MySQLdb 1.2.2: http://sourceforge.net/tracker/index.php?func=detail&aid=1495765&group_id=22307&atid=374932
  191. Connecting to the database
  192. --------------------------
  193. Refer to the :ref:`settings documentation <ref-settings>`.
  194. Connection settings are used in this order:
  195. 1. :setting:`OPTIONS`.
  196. 2. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`,
  197. :setting:`HOST`, :setting:`PORT`
  198. 3. MySQL option files.
  199. In other words, if you set the name of the database in ``OPTIONS``,
  200. this will take precedence over ``NAME``, which would override
  201. anything in a `MySQL option file`_.
  202. Here's a sample configuration which uses a MySQL option file::
  203. # settings.py
  204. DATABASES = {
  205. 'default': {
  206. 'ENGINE': 'django.db.backends.mysql',
  207. 'OPTIONS': {
  208. 'read_default_file': '/path/to/my.cnf',
  209. },
  210. }
  211. }
  212. # my.cnf
  213. [client]
  214. database = NAME
  215. user = USER
  216. password = PASSWORD
  217. default-character-set = utf8
  218. Several other MySQLdb connection options may be useful, such as ``ssl``,
  219. ``use_unicode``, ``init_command``, and ``sql_mode``. Consult the
  220. `MySQLdb documentation`_ for more details.
  221. .. _MySQL option file: http://dev.mysql.com/doc/refman/5.0/en/option-files.html
  222. .. _MySQLdb documentation: http://mysql-python.sourceforge.net/
  223. Creating your tables
  224. --------------------
  225. When Django generates the schema, it doesn't specify a storage engine, so
  226. tables will be created with whatever default storage engine your database
  227. server is configured for. The easiest solution is to set your database server's
  228. default storage engine to the desired engine.
  229. If you're using a hosting service and can't change your server's default
  230. storage engine, you have a couple of options.
  231. * After the tables are created, execute an ``ALTER TABLE`` statement to
  232. convert a table to a new storage engine (such as InnoDB)::
  233. ALTER TABLE <tablename> ENGINE=INNODB;
  234. This can be tedious if you have a lot of tables.
  235. * Another option is to use the ``init_command`` option for MySQLdb prior to
  236. creating your tables::
  237. OPTIONS = {
  238. "init_command": "SET storage_engine=INNODB",
  239. }
  240. This sets the default storage engine upon connecting to the database.
  241. After your tables have been created, you should remove this option.
  242. * Another method for changing the storage engine is described in
  243. AlterModelOnSyncDB_.
  244. .. _AlterModelOnSyncDB: http://code.djangoproject.com/wiki/AlterModelOnSyncDB
  245. Notes on specific fields
  246. ------------------------
  247. Boolean fields
  248. ~~~~~~~~~~~~~~
  249. Since MySQL doesn't have a direct ``BOOLEAN`` column type, Django uses a
  250. ``TINYINT`` column with values of ``1`` and ``0`` to store values for the
  251. :class:`~django.db.models.BooleanField` model field. Refer to the documentation
  252. of that field for more details, but usually this won't be something that will
  253. matter unless you're printing out the field values and are expecting to see
  254. ``True`` and ``False.``.
  255. Character fields
  256. ~~~~~~~~~~~~~~~~
  257. Any fields that are stored with ``VARCHAR`` column types have their
  258. ``max_length`` restricted to 255 characters if you are using ``unique=True``
  259. for the field. This affects :class:`~django.db.models.CharField`,
  260. :class:`~django.db.models.SlugField` and
  261. :class:`~django.db.models.CommaSeparatedIntegerField`.
  262. Furthermore, if you are using a version of MySQL prior to 5.0.3, all of those
  263. column types have a maximum length restriction of 255 characters, regardless
  264. of whether ``unique=True`` is specified or not.
  265. .. _sqlite-notes:
  266. SQLite notes
  267. ============
  268. SQLite_ provides an excellent development alternative for applications that
  269. are predominantly read-only or require a smaller installation footprint. As
  270. with all database servers, though, there are some differences that are
  271. specific to SQLite that you should be aware of.
  272. .. _SQLite: http://www.sqlite.org/
  273. .. _sqlite-string-matching:
  274. String matching for non-ASCII strings
  275. --------------------------------------
  276. SQLite doesn't support case-insensitive matching for non-ASCII strings. Some
  277. possible workarounds for this are `documented at sqlite.org`_, but they are
  278. not utilised by the default SQLite backend in Django. Therefore, if you are
  279. using the ``iexact`` lookup type in your queryset filters, be aware that it
  280. will not work as expected for non-ASCII strings.
  281. .. _documented at sqlite.org: http://www.sqlite.org/faq.html#q18
  282. SQLite 3.3.6 or newer strongly recommended
  283. ------------------------------------------
  284. Versions of SQLite 3.3.5 and older contains the following bugs:
  285. * A bug when `handling`_ ``ORDER BY`` parameters. This can cause problems when
  286. you use the ``select`` parameter for the ``extra()`` QuerySet method. The bug
  287. can be identified by the error message ``OperationalError: ORDER BY terms
  288. must not be non-integer constants``.
  289. * A bug when handling `aggregation`_ together with DateFields and
  290. DecimalFields.
  291. .. _handling: http://www.sqlite.org/cvstrac/tktview?tn=1768
  292. .. _aggregation: http://code.djangoproject.com/ticket/10031
  293. SQLite 3.3.6 was released in April 2006, so most current binary distributions
  294. for different platforms include newer version of SQLite usable from Python
  295. through either the ``pysqlite2`` or the ``sqlite3`` modules.
  296. However, some platform/Python version combinations include older versions of
  297. SQLite (e.g. the official binary distribution of Python 2.5 for Windows, 2.5.4
  298. as of this writing, includes SQLite 3.3.4). There are (as of Django 1.1) even
  299. some tests in the Django test suite that will fail when run under this setup.
  300. As described :ref:`below<using-newer-versions-of-pysqlite>`, this can be solved
  301. by downloading and installing a newer version of ``pysqlite2``
  302. (``pysqlite-2.x.x.win32-py2.5.exe`` in the described case) that includes and
  303. uses a newer version of SQLite. Python 2.6 for Windows ships with a version of
  304. SQLite that is not affected by these issues.
  305. Version 3.5.9
  306. -------------
  307. The Ubuntu "Intrepid Ibex" (8.10) SQLite 3.5.9-3 package contains a bug that
  308. causes problems with the evaluation of query expressions. If you are using
  309. Ubuntu "Intrepid Ibex", you will need to update the package to version
  310. 3.5.9-3ubuntu1 or newer (recommended) or find an alternate source for SQLite
  311. packages, or install SQLite from source.
  312. At one time, Debian Lenny shipped with the same malfunctioning SQLite 3.5.9-3
  313. package. However the Debian project has subsequently issued updated versions
  314. of the SQLite package that correct these bugs. If you find you are getting
  315. unexpected results under Debian, ensure you have updated your SQLite package
  316. to 3.5.9-5 or later.
  317. The problem does not appear to exist with other versions of SQLite packaged
  318. with other operating systems.
  319. Version 3.6.2
  320. --------------
  321. SQLite version 3.6.2 (released August 30, 2008) introduced a bug into ``SELECT
  322. DISTINCT`` handling that is triggered by, amongst other things, Django's
  323. ``DateQuerySet`` (returned by the ``dates()`` method on a queryset).
  324. You should avoid using this version of SQLite with Django. Either upgrade to
  325. 3.6.3 (released September 22, 2008) or later, or downgrade to an earlier
  326. version of SQLite.
  327. .. _using-newer-versions-of-pysqlite:
  328. Using newer versions of the SQLite DB-API 2.0 driver
  329. ----------------------------------------------------
  330. .. versionadded:: 1.1
  331. For versions of Python 2.5 or newer that include ``sqlite3`` in the standard
  332. library Django will now use a ``pysqlite2`` interface in preference to
  333. ``sqlite3`` if it finds one is available.
  334. This provides the ability to upgrade both the DB-API 2.0 interface or SQLite 3
  335. itself to versions newer than the ones included with your particular Python
  336. binary distribution, if needed.
  337. "Database is locked" errors
  338. -----------------------------------------------
  339. SQLite is meant to be a lightweight database, and thus can't support a high
  340. level of concurrency. ``OperationalError: database is locked`` errors indicate
  341. that your application is experiencing more concurrency than ``sqlite`` can
  342. handle in default configuration. This error means that one thread or process has
  343. an exclusive lock on the database connection and another thread timed out
  344. waiting for the lock the be released.
  345. Python's SQLite wrapper has
  346. a default timeout value that determines how long the second thread is allowed to
  347. wait on the lock before it times out and raises the ``OperationalError: database
  348. is locked`` error.
  349. If you're getting this error, you can solve it by:
  350. * Switching to another database backend. At a certain point SQLite becomes
  351. too "lite" for real-world applications, and these sorts of concurrency
  352. errors indicate you've reached that point.
  353. * Rewriting your code to reduce concurrency and ensure that database
  354. transactions are short-lived.
  355. * Increase the default timeout value by setting the ``timeout`` database
  356. option option::
  357. OPTIONS = {
  358. # ...
  359. "timeout": 20,
  360. # ...
  361. }
  362. This will simply make SQLite wait a bit longer before throwing "database
  363. is locked" errors; it won't really do anything to solve them.
  364. .. _oracle-notes:
  365. Oracle notes
  366. ============
  367. Django supports `Oracle Database Server`_ versions 9i and
  368. higher. Oracle version 10g or later is required to use Django's
  369. ``regex`` and ``iregex`` query operators. You will also need at least
  370. version 4.3.1 of the `cx_Oracle`_ Python driver.
  371. Note that due to a Unicode-corruption bug in ``cx_Oracle`` 5.0, that
  372. version of the driver should **not** be used with Django;
  373. ``cx_Oracle`` 5.0.1 resolved this issue, so if you'd like to use a
  374. more recent ``cx_Oracle``, use version 5.0.1.
  375. ``cx_Oracle`` 5.0.1 or greater can optionally be compiled with the
  376. ``WITH_UNICODE`` environment variable. This is recommended but not
  377. required.
  378. .. _`Oracle Database Server`: http://www.oracle.com/
  379. .. _`cx_Oracle`: http://cx-oracle.sourceforge.net/
  380. In order for the ``python manage.py syncdb`` command to work, your Oracle
  381. database user must have privileges to run the following commands:
  382. * CREATE TABLE
  383. * CREATE SEQUENCE
  384. * CREATE PROCEDURE
  385. * CREATE TRIGGER
  386. To run Django's test suite, the user needs these *additional* privileges:
  387. * CREATE USER
  388. * DROP USER
  389. * CREATE TABLESPACE
  390. * DROP TABLESPACE
  391. * CONNECT WITH ADMIN OPTION
  392. * RESOURCE WITH ADMIN OPTION
  393. Connecting to the database
  394. --------------------------
  395. Your Django settings.py file should look something like this for Oracle::
  396. DATABASES = {
  397. 'default': {
  398. 'ENGINE': 'django.db.backends.oracle',
  399. 'NAME': 'xe',
  400. 'USER': 'a_user',
  401. 'PASSWORD': 'a_password',
  402. 'HOST': '',
  403. 'PORT': '' ,
  404. }
  405. }
  406. If you don't use a ``tnsnames.ora`` file or a similar naming method that
  407. recognizes the SID ("xe" in this example), then fill in both
  408. ``HOST`` and ``PORT`` like so::
  409. DATABASES = {
  410. 'default': {
  411. 'ENGINE': 'django.db.backends.oracle',
  412. 'NAME': 'xe',
  413. 'USER': 'a_user',
  414. 'PASSWORD': 'a_password',
  415. 'HOST': 'dbprod01ned.mycompany.com',
  416. 'PORT': '1540',
  417. }
  418. }
  419. You should supply both ``HOST`` and ``PORT``, or leave both
  420. as empty strings.
  421. Tablespace options
  422. ------------------
  423. A common paradigm for optimizing performance in Oracle-based systems is the
  424. use of `tablespaces`_ to organize disk layout. The Oracle backend supports
  425. this use case by adding ``db_tablespace`` options to the ``Meta`` and
  426. ``Field`` classes. (When you use a backend that lacks support for tablespaces,
  427. Django ignores these options.)
  428. .. _`tablespaces`: http://en.wikipedia.org/wiki/Tablespace
  429. A tablespace can be specified for the table(s) generated by a model by
  430. supplying the ``db_tablespace`` option inside the model's ``class Meta``.
  431. Additionally, you can pass the ``db_tablespace`` option to a ``Field``
  432. constructor to specify an alternate tablespace for the ``Field``'s column
  433. index. If no index would be created for the column, the ``db_tablespace``
  434. option is ignored::
  435. class TablespaceExample(models.Model):
  436. name = models.CharField(max_length=30, db_index=True, db_tablespace="indexes")
  437. data = models.CharField(max_length=255, db_index=True)
  438. edges = models.ManyToManyField(to="self", db_tablespace="indexes")
  439. class Meta:
  440. db_tablespace = "tables"
  441. In this example, the tables generated by the ``TablespaceExample`` model
  442. (i.e., the model table and the many-to-many table) would be stored in the
  443. ``tables`` tablespace. The index for the name field and the indexes on the
  444. many-to-many table would be stored in the ``indexes`` tablespace. The ``data``
  445. field would also generate an index, but no tablespace for it is specified, so
  446. it would be stored in the model tablespace ``tables`` by default.
  447. .. versionadded:: 1.0
  448. Use the :setting:`DEFAULT_TABLESPACE` and :setting:`DEFAULT_INDEX_TABLESPACE`
  449. settings to specify default values for the db_tablespace options.
  450. These are useful for setting a tablespace for the built-in Django apps and
  451. other applications whose code you cannot control.
  452. Django does not create the tablespaces for you. Please refer to `Oracle's
  453. documentation`_ for details on creating and managing tablespaces.
  454. .. _`Oracle's documentation`: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7003.htm#SQLRF01403
  455. Naming issues
  456. -------------
  457. Oracle imposes a name length limit of 30 characters. To accommodate this, the
  458. backend truncates database identifiers to fit, replacing the final four
  459. characters of the truncated name with a repeatable MD5 hash value.
  460. NULL and empty strings
  461. ----------------------
  462. Django generally prefers to use the empty string ('') rather than
  463. NULL, but Oracle treats both identically. To get around this, the
  464. Oracle backend coerces the ``null=True`` option on fields that have
  465. the empty string as a possible value. When fetching from the database,
  466. it is assumed that a NULL value in one of these fields really means
  467. the empty string, and the data is silently converted to reflect this
  468. assumption.
  469. ``TextField`` limitations
  470. -------------------------
  471. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
  472. some limitations on the usage of such LOB columns in general:
  473. * LOB columns may not be used as primary keys.
  474. * LOB columns may not be used in indexes.
  475. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
  476. attempting to use the ``QuerySet.distinct`` method on a model that
  477. includes ``TextField`` columns will result in an error when run against
  478. Oracle. A workaround to this is to keep ``TextField`` columns out of any
  479. models that you foresee performing ``distinct()`` queries on, and to
  480. include the ``TextField`` in a related model instead.
  481. .. _third-party-notes:
  482. Using a 3rd-party database backend
  483. ==================================
  484. In addition to the officially supported databases, there are backends provided
  485. by 3rd parties that allow you to use other databases with Django:
  486. * `Sybase SQL Anywhere`_
  487. * `IBM DB2`_
  488. * `Microsoft SQL Server 2005`_
  489. * Firebird_
  490. * ODBC_
  491. The Django versions and ORM features supported by these unofficial backends
  492. vary considerably. Queries regarding the specific capabilities of these
  493. unofficial backends, along with any support queries, should be directed to
  494. the support channels provided by each 3rd party project.
  495. .. _Sybase SQL Anywhere: http://code.google.com/p/sqlany-django/
  496. .. _IBM DB2: http://code.google.com/p/ibm-db/
  497. .. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/
  498. .. _Firebird: http://code.google.com/p/django-firebird/
  499. .. _ODBC: http://code.google.com/p/django-pyodbc/