PageRenderTime 30ms CodeModel.GetById 18ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/ref/databases.txt

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