1. =========
    
  2. Databases
    
  3. =========
    
  4. 
    
  5. Django officially supports the following databases:
    
  6. 
    
  7. * :ref:`PostgreSQL <postgresql-notes>`
    
  8. * :ref:`MariaDB <mariadb-notes>`
    
  9. * :ref:`MySQL <mysql-notes>`
    
  10. * :ref:`Oracle <oracle-notes>`
    
  11. * :ref:`SQLite <sqlite-notes>`
    
  12. 
    
  13. There are also a number of :ref:`database backends provided by third parties
    
  14. <third-party-notes>`.
    
  15. 
    
  16. Django attempts to support as many features as possible on all database
    
  17. backends. However, not all database backends are alike, and we've had to make
    
  18. design decisions on which features to support and which assumptions we can make
    
  19. safely.
    
  20. 
    
  21. This file describes some of the features that might be relevant to Django
    
  22. usage. It is not intended as a replacement for server-specific documentation or
    
  23. reference manuals.
    
  24. 
    
  25. General notes
    
  26. =============
    
  27. 
    
  28. .. _persistent-database-connections:
    
  29. 
    
  30. Persistent connections
    
  31. ----------------------
    
  32. 
    
  33. Persistent connections avoid the overhead of reestablishing a connection to
    
  34. the database in each request. They're controlled by the
    
  35. :setting:`CONN_MAX_AGE` parameter which defines the maximum lifetime of a
    
  36. connection. It can be set independently for each database.
    
  37. 
    
  38. The default value is ``0``, preserving the historical behavior of closing the
    
  39. database connection at the end of each request. To enable persistent
    
  40. connections, set :setting:`CONN_MAX_AGE` to a positive integer of seconds. For
    
  41. unlimited persistent connections, set it to ``None``.
    
  42. 
    
  43. Connection management
    
  44. ~~~~~~~~~~~~~~~~~~~~~
    
  45. 
    
  46. Django opens a connection to the database when it first makes a database
    
  47. query. It keeps this connection open and reuses it in subsequent requests.
    
  48. Django closes the connection once it exceeds the maximum age defined by
    
  49. :setting:`CONN_MAX_AGE` or when it isn't usable any longer.
    
  50. 
    
  51. In detail, Django automatically opens a connection to the database whenever it
    
  52. needs one and doesn't have one already — either because this is the first
    
  53. connection, or because the previous connection was closed.
    
  54. 
    
  55. At the beginning of each request, Django closes the connection if it has
    
  56. reached its maximum age. If your database terminates idle connections after
    
  57. some time, you should set :setting:`CONN_MAX_AGE` to a lower value, so that
    
  58. Django doesn't attempt to use a connection that has been terminated by the
    
  59. database server. (This problem may only affect very low traffic sites.)
    
  60. 
    
  61. At the end of each request, Django closes the connection if it has reached its
    
  62. maximum age or if it is in an unrecoverable error state. If any database
    
  63. errors have occurred while processing the requests, Django checks whether the
    
  64. connection still works, and closes it if it doesn't. Thus, database errors
    
  65. affect at most one request per each application's worker thread; if the
    
  66. connection becomes unusable, the next request gets a fresh connection.
    
  67. 
    
  68. Setting :setting:`CONN_HEALTH_CHECKS` to ``True`` can be used to improve the
    
  69. robustness of connection reuse and prevent errors when a connection has been
    
  70. closed by the database server which is now ready to accept and serve new
    
  71. connections, e.g. after database server restart. The health check is performed
    
  72. only once per request and only if the database is being accessed during the
    
  73. handling of the request.
    
  74. 
    
  75. .. versionchanged:: 4.1
    
  76. 
    
  77.     The :setting:`CONN_HEALTH_CHECKS` setting was added.
    
  78. 
    
  79. Caveats
    
  80. ~~~~~~~
    
  81. 
    
  82. Since each thread maintains its own connection, your database must support at
    
  83. least as many simultaneous connections as you have worker threads.
    
  84. 
    
  85. Sometimes a database won't be accessed by the majority of your views, for
    
  86. example because it's the database of an external system, or thanks to caching.
    
  87. In such cases, you should set :setting:`CONN_MAX_AGE` to a low value or even
    
  88. ``0``, because it doesn't make sense to maintain a connection that's unlikely
    
  89. to be reused. This will help keep the number of simultaneous connections to
    
  90. this database small.
    
  91. 
    
  92. The development server creates a new thread for each request it handles,
    
  93. negating the effect of persistent connections. Don't enable them during
    
  94. development.
    
  95. 
    
  96. When Django establishes a connection to the database, it sets up appropriate
    
  97. parameters, depending on the backend being used. If you enable persistent
    
  98. connections, this setup is no longer repeated every request. If you modify
    
  99. parameters such as the connection's isolation level or time zone, you should
    
  100. either restore Django's defaults at the end of each request, force an
    
  101. appropriate value at the beginning of each request, or disable persistent
    
  102. connections.
    
  103. 
    
  104. Encoding
    
  105. --------
    
  106. 
    
  107. Django assumes that all databases use UTF-8 encoding. Using other encodings may
    
  108. result in unexpected behavior such as "value too long" errors from your
    
  109. database for data that is valid in Django. See the database specific notes
    
  110. below for information on how to set up your database correctly.
    
  111. 
    
  112. .. _postgresql-notes:
    
  113. 
    
  114. PostgreSQL notes
    
  115. ================
    
  116. 
    
  117. Django supports PostgreSQL 11 and higher. `psycopg2`_ 2.8.4 or higher is
    
  118. required, though the latest release is recommended.
    
  119. 
    
  120. .. _psycopg2: https://www.psycopg.org/
    
  121. 
    
  122. .. _postgresql-connection-settings:
    
  123. 
    
  124. PostgreSQL connection settings
    
  125. -------------------------------
    
  126. 
    
  127. See :setting:`HOST` for details.
    
  128. 
    
  129. To connect using a service name from the `connection service file`_ and a
    
  130. password from the `password file`_, you must specify them in the
    
  131. :setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`:
    
  132. 
    
  133. .. code-block:: python
    
  134.     :caption: ``settings.py``
    
  135. 
    
  136.     DATABASES = {
    
  137.         'default': {
    
  138.             'ENGINE': 'django.db.backends.postgresql',
    
  139.             'OPTIONS': {
    
  140.                 'service': 'my_service',
    
  141.                 'passfile': '.my_pgpass',
    
  142.             },
    
  143.         }
    
  144.     }
    
  145. 
    
  146. .. code-block:: text
    
  147.     :caption: ``.pg_service.conf``
    
  148. 
    
  149.     [my_service]
    
  150.     host=localhost
    
  151.     user=USER
    
  152.     dbname=NAME
    
  153.     port=5432
    
  154. 
    
  155. .. code-block:: text
    
  156.     :caption: ``.my_pgpass``
    
  157. 
    
  158.     localhost:5432:NAME:USER:PASSWORD
    
  159. 
    
  160. .. _connection service file: https://www.postgresql.org/docs/current/libpq-pgservice.html
    
  161. .. _password file: https://www.postgresql.org/docs/current/libpq-pgpass.html
    
  162. 
    
  163. .. versionchanged:: 4.0
    
  164. 
    
  165.     Support for connecting by a service name, and specifying a password file
    
  166.     was added.
    
  167. 
    
  168. .. warning::
    
  169. 
    
  170.     Using a service name for testing purposes is not supported. This
    
  171.     :ticket:`may be implemented later <33685>`.
    
  172. 
    
  173. Optimizing PostgreSQL's configuration
    
  174. -------------------------------------
    
  175. 
    
  176. Django needs the following parameters for its database connections:
    
  177. 
    
  178. - ``client_encoding``: ``'UTF8'``,
    
  179. - ``default_transaction_isolation``: ``'read committed'`` by default,
    
  180.   or the value set in the connection options (see below),
    
  181. - ``timezone``:
    
  182.     - when :setting:`USE_TZ` is ``True``, ``'UTC'`` by default, or the
    
  183.       :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` value set for the connection,
    
  184.     - when :setting:`USE_TZ` is ``False``, the value of the global
    
  185.       :setting:`TIME_ZONE` setting.
    
  186. 
    
  187. If these parameters already have the correct values, Django won't set them for
    
  188. every new connection, which improves performance slightly. You can configure
    
  189. them directly in :file:`postgresql.conf` or more conveniently per database
    
  190. user with `ALTER ROLE`_.
    
  191. 
    
  192. Django will work just fine without this optimization, but each new connection
    
  193. will do some additional queries to set these parameters.
    
  194. 
    
  195. .. _ALTER ROLE: https://www.postgresql.org/docs/current/sql-alterrole.html
    
  196. 
    
  197. .. _database-isolation-level:
    
  198. 
    
  199. Isolation level
    
  200. ---------------
    
  201. 
    
  202. Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
    
  203. level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
    
  204. ``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
    
  205. configuration in :setting:`DATABASES`::
    
  206. 
    
  207.     import psycopg2.extensions
    
  208. 
    
  209.     DATABASES = {
    
  210.         # ...
    
  211.         'OPTIONS': {
    
  212.             'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
    
  213.         },
    
  214.     }
    
  215. 
    
  216. .. note::
    
  217. 
    
  218.     Under higher isolation levels, your application should be prepared to
    
  219.     handle exceptions raised on serialization failures. This option is
    
  220.     designed for advanced uses.
    
  221. 
    
  222. .. _isolation level: https://www.postgresql.org/docs/current/transaction-iso.html
    
  223. 
    
  224. Indexes for ``varchar`` and ``text`` columns
    
  225. --------------------------------------------
    
  226. 
    
  227. When specifying ``db_index=True`` on your model fields, Django typically
    
  228. outputs a single ``CREATE INDEX`` statement.  However, if the database type
    
  229. for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
    
  230. ``FileField``, and ``TextField``), then Django will create
    
  231. an additional index that uses an appropriate `PostgreSQL operator class`_
    
  232. for the column.  The extra index is necessary to correctly perform
    
  233. lookups that use the ``LIKE`` operator in their SQL, as is done with the
    
  234. ``contains`` and ``startswith`` lookup types.
    
  235. 
    
  236. .. _PostgreSQL operator class: https://www.postgresql.org/docs/current/indexes-opclass.html
    
  237. 
    
  238. Migration operation for adding extensions
    
  239. -----------------------------------------
    
  240. 
    
  241. If you need to add a PostgreSQL extension (like ``hstore``, ``postgis``, etc.)
    
  242. using a migration, use the
    
  243. :class:`~django.contrib.postgres.operations.CreateExtension` operation.
    
  244. 
    
  245. .. _postgresql-server-side-cursors:
    
  246. 
    
  247. Server-side cursors
    
  248. -------------------
    
  249. 
    
  250. When using :meth:`QuerySet.iterator()
    
  251. <django.db.models.query.QuerySet.iterator>`, Django opens a :ref:`server-side
    
  252. cursor <psycopg2:server-side-cursors>`. By default, PostgreSQL assumes that
    
  253. only the first 10% of the results of cursor queries will be fetched. The query
    
  254. planner spends less time planning the query and starts returning results
    
  255. faster, but this could diminish performance if more than 10% of the results are
    
  256. retrieved. PostgreSQL's assumptions on the number of rows retrieved for a
    
  257. cursor query is controlled with the `cursor_tuple_fraction`_ option.
    
  258. 
    
  259. .. _cursor_tuple_fraction: https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-CURSOR-TUPLE-FRACTION
    
  260. 
    
  261. .. _transaction-pooling-server-side-cursors:
    
  262. 
    
  263. Transaction pooling and server-side cursors
    
  264. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  265. 
    
  266. Using a connection pooler in transaction pooling mode (e.g. `PgBouncer`_)
    
  267. requires disabling server-side cursors for that connection.
    
  268. 
    
  269. Server-side cursors are local to a connection and remain open at the end of a
    
  270. transaction when :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` is ``True``. A
    
  271. subsequent transaction may attempt to fetch more results from a server-side
    
  272. cursor. In transaction pooling mode, there's no guarantee that subsequent
    
  273. transactions will use the same connection. If a different connection is used,
    
  274. an error is raised when the transaction references the server-side cursor,
    
  275. because server-side cursors are only accessible in the connection in which they
    
  276. were created.
    
  277. 
    
  278. One solution is to disable server-side cursors for a connection in
    
  279. :setting:`DATABASES` by setting :setting:`DISABLE_SERVER_SIDE_CURSORS
    
  280. <DATABASE-DISABLE_SERVER_SIDE_CURSORS>` to ``True``.
    
  281. 
    
  282. To benefit from server-side cursors in transaction pooling mode, you could set
    
  283. up :doc:`another connection to the database </topics/db/multi-db>` in order to
    
  284. perform queries that use server-side cursors. This connection needs to either
    
  285. be directly to the database or to a connection pooler in session pooling mode.
    
  286. 
    
  287. Another option is to wrap each ``QuerySet`` using server-side cursors in an
    
  288. :func:`~django.db.transaction.atomic` block, because it disables ``autocommit``
    
  289. for the duration of the transaction. This way, the server-side cursor will only
    
  290. live for the duration of the transaction.
    
  291. 
    
  292. .. _PgBouncer: https://www.pgbouncer.org/
    
  293. 
    
  294. .. _manually-specified-autoincrement-pk:
    
  295. 
    
  296. Manually-specifying values of auto-incrementing primary keys
    
  297. ------------------------------------------------------------
    
  298. 
    
  299. Django uses PostgreSQL's identity columns to store auto-incrementing primary
    
  300. keys. An identity column is populated with values from a `sequence`_ that keeps
    
  301. track of the next available value. Manually assigning a value to an
    
  302. auto-incrementing field doesn't update the field's sequence, which might later
    
  303. cause a conflict. For example::
    
  304. 
    
  305.     >>> from django.contrib.auth.models import User
    
  306.     >>> User.objects.create(username='alice', pk=1)
    
  307.     <User: alice>
    
  308.     >>> # The sequence hasn't been updated; its next value is 1.
    
  309.     >>> User.objects.create(username='bob')
    
  310.     ...
    
  311.     IntegrityError: duplicate key value violates unique constraint
    
  312.     "auth_user_pkey" DETAIL:  Key (id)=(1) already exists.
    
  313. 
    
  314. If you need to specify such values, reset the sequence afterward to avoid
    
  315. reusing a value that's already in the table. The :djadmin:`sqlsequencereset`
    
  316. management command generates the SQL statements to do that.
    
  317. 
    
  318. .. versionchanged:: 4.1
    
  319. 
    
  320.     In older versions, PostgreSQL’s ``SERIAL`` data type was used instead of
    
  321.     identity columns.
    
  322. 
    
  323. .. _sequence: https://www.postgresql.org/docs/current/sql-createsequence.html
    
  324. 
    
  325. Test database templates
    
  326. -----------------------
    
  327. 
    
  328. You can use the :setting:`TEST['TEMPLATE'] <TEST_TEMPLATE>` setting to specify
    
  329. a `template`_ (e.g. ``'template0'``) from which to create a test database.
    
  330. 
    
  331. .. _template: https://www.postgresql.org/docs/current/sql-createdatabase.html
    
  332. 
    
  333. Speeding up test execution with non-durable settings
    
  334. ----------------------------------------------------
    
  335. 
    
  336. You can speed up test execution times by `configuring PostgreSQL to be
    
  337. non-durable <https://www.postgresql.org/docs/current/non-durability.html>`_.
    
  338. 
    
  339. .. warning::
    
  340. 
    
  341.     This is dangerous: it will make your database more susceptible to data loss
    
  342.     or corruption in the case of a server crash or power loss. Only use this on
    
  343.     a development machine where you can easily restore the entire contents of
    
  344.     all databases in the cluster.
    
  345. 
    
  346. .. _mariadb-notes:
    
  347. 
    
  348. MariaDB notes
    
  349. =============
    
  350. 
    
  351. Django supports MariaDB 10.3 and higher.
    
  352. 
    
  353. To use MariaDB, use the MySQL backend, which is shared between the two. See the
    
  354. :ref:`MySQL notes <mysql-notes>` for more details.
    
  355. 
    
  356. .. _mysql-notes:
    
  357. 
    
  358. MySQL notes
    
  359. ===========
    
  360. 
    
  361. Version support
    
  362. ---------------
    
  363. 
    
  364. Django supports MySQL 5.7 and higher.
    
  365. 
    
  366. Django's ``inspectdb`` feature uses the ``information_schema`` database, which
    
  367. contains detailed data on all database schemas.
    
  368. 
    
  369. Django expects the database to support Unicode (UTF-8 encoding) and delegates to
    
  370. it the task of enforcing transactions and referential integrity. It is important
    
  371. to be aware of the fact that the two latter ones aren't actually enforced by
    
  372. MySQL when using the MyISAM storage engine, see the next section.
    
  373. 
    
  374. .. _mysql-storage-engines:
    
  375. 
    
  376. Storage engines
    
  377. ---------------
    
  378. 
    
  379. MySQL has several `storage engines`_. You can change the default storage engine
    
  380. in the server configuration.
    
  381. 
    
  382. MySQL's default storage engine is InnoDB_. This engine is fully transactional
    
  383. and supports foreign key references. It's the recommended choice. However, the
    
  384. InnoDB autoincrement counter is lost on a MySQL restart because it does not
    
  385. remember the ``AUTO_INCREMENT`` value, instead recreating it as "max(id)+1".
    
  386. This may result in an inadvertent reuse of :class:`~django.db.models.AutoField`
    
  387. values.
    
  388. 
    
  389. The main drawbacks of MyISAM_ are that it doesn't support transactions or
    
  390. enforce foreign-key constraints.
    
  391. 
    
  392. .. _storage engines: https://dev.mysql.com/doc/refman/en/storage-engines.html
    
  393. .. _MyISAM: https://dev.mysql.com/doc/refman/en/myisam-storage-engine.html
    
  394. .. _InnoDB: https://dev.mysql.com/doc/refman/en/innodb-storage-engine.html
    
  395. 
    
  396. .. _mysql-db-api-drivers:
    
  397. 
    
  398. MySQL DB API Drivers
    
  399. --------------------
    
  400. 
    
  401. MySQL has a couple drivers that implement the Python Database API described in
    
  402. :pep:`249`:
    
  403. 
    
  404. - `mysqlclient`_ is a native driver. It's **the recommended choice**.
    
  405. - `MySQL Connector/Python`_ is a pure Python driver from Oracle that does not
    
  406.   require the MySQL client library or any Python modules outside the standard
    
  407.   library.
    
  408. 
    
  409. .. _mysqlclient: https://pypi.org/project/mysqlclient/
    
  410. .. _MySQL Connector/Python: https://dev.mysql.com/downloads/connector/python/
    
  411. 
    
  412. These drivers are thread-safe and provide connection pooling.
    
  413. 
    
  414. In addition to a DB API driver, Django needs an adapter to access the database
    
  415. drivers from its ORM. Django provides an adapter for mysqlclient while MySQL
    
  416. Connector/Python includes `its own`_.
    
  417. 
    
  418. .. _its own: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html
    
  419. 
    
  420. mysqlclient
    
  421. ~~~~~~~~~~~
    
  422. 
    
  423. Django requires `mysqlclient`_ 1.4.0 or later.
    
  424. 
    
  425. MySQL Connector/Python
    
  426. ~~~~~~~~~~~~~~~~~~~~~~
    
  427. 
    
  428. MySQL Connector/Python is available from the `download page`_.
    
  429. The Django adapter is available in versions 1.1.X and later. It may not
    
  430. support the most recent releases of Django.
    
  431. 
    
  432. .. _download page: https://dev.mysql.com/downloads/connector/python/
    
  433. 
    
  434. .. _mysql-time-zone-definitions:
    
  435. 
    
  436. Time zone definitions
    
  437. ---------------------
    
  438. 
    
  439. If you plan on using Django's :doc:`timezone support </topics/i18n/timezones>`,
    
  440. use `mysql_tzinfo_to_sql`_ to load time zone tables into the MySQL database.
    
  441. This needs to be done just once for your MySQL server, not per database.
    
  442. 
    
  443. .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
    
  444. 
    
  445. Creating your database
    
  446. ----------------------
    
  447. 
    
  448. You can `create your database`_ using the command-line tools and this SQL::
    
  449. 
    
  450.   CREATE DATABASE <dbname> CHARACTER SET utf8;
    
  451. 
    
  452. This ensures all tables and columns will use UTF-8 by default.
    
  453. 
    
  454. .. _create your database: https://dev.mysql.com/doc/refman/en/create-database.html
    
  455. 
    
  456. .. _mysql-collation:
    
  457. 
    
  458. Collation settings
    
  459. ~~~~~~~~~~~~~~~~~~
    
  460. 
    
  461. The collation setting for a column controls the order in which data is sorted
    
  462. as well as what strings compare as equal. You can specify the ``db_collation``
    
  463. parameter to set the collation name of the column for
    
  464. :attr:`CharField <django.db.models.CharField.db_collation>` and
    
  465. :attr:`TextField <django.db.models.TextField.db_collation>`.
    
  466. 
    
  467. The collation can also be set on a database-wide level and per-table. This is
    
  468. `documented thoroughly`_ in the MySQL documentation. In such cases, you must
    
  469. set the collation by directly manipulating the database settings or tables.
    
  470. Django doesn't provide an API to change them.
    
  471. 
    
  472. .. _documented thoroughly: https://dev.mysql.com/doc/refman/en/charset.html
    
  473. 
    
  474. By default, with a UTF-8 database, MySQL will use the
    
  475. ``utf8_general_ci`` collation. This results in all string equality
    
  476. comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
    
  477. ``"freD"`` are considered equal at the database level. If you have a unique
    
  478. constraint on a field, it would be illegal to try to insert both ``"aa"`` and
    
  479. ``"AA"`` into the same column, since they compare as equal (and, hence,
    
  480. non-unique) with the default collation. If you want case-sensitive comparisons
    
  481. on a particular column or table, change the column or table to use the
    
  482. ``utf8_bin`` collation.
    
  483. 
    
  484. Please note that according to `MySQL Unicode Character Sets`_, comparisons for
    
  485. the ``utf8_general_ci`` collation are faster, but slightly less correct, than
    
  486. comparisons for ``utf8_unicode_ci``. If this is acceptable for your application,
    
  487. you should use ``utf8_general_ci`` because it is faster. If this is not acceptable
    
  488. (for example, if you require German dictionary order), use ``utf8_unicode_ci``
    
  489. because it is more accurate.
    
  490. 
    
  491. .. _MySQL Unicode Character Sets: https://dev.mysql.com/doc/refman/en/charset-unicode-sets.html
    
  492. 
    
  493. .. warning::
    
  494. 
    
  495.     Model formsets validate unique fields in a case-sensitive manner. Thus when
    
  496.     using a case-insensitive collation, a formset with unique field values that
    
  497.     differ only by case will pass validation, but upon calling ``save()``, an
    
  498.     ``IntegrityError`` will be raised.
    
  499. 
    
  500. Connecting to the database
    
  501. --------------------------
    
  502. 
    
  503. Refer to the :doc:`settings documentation </ref/settings>`.
    
  504. 
    
  505. Connection settings are used in this order:
    
  506. 
    
  507. #. :setting:`OPTIONS`.
    
  508. #. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`, :setting:`HOST`,
    
  509.    :setting:`PORT`
    
  510. #. MySQL option files.
    
  511. 
    
  512. In other words, if you set the name of the database in :setting:`OPTIONS`,
    
  513. this will take precedence over :setting:`NAME`, which would override
    
  514. anything in a `MySQL option file`_.
    
  515. 
    
  516. Here's a sample configuration which uses a MySQL option file::
    
  517. 
    
  518.     # settings.py
    
  519.     DATABASES = {
    
  520.         'default': {
    
  521.             'ENGINE': 'django.db.backends.mysql',
    
  522.             'OPTIONS': {
    
  523.                 'read_default_file': '/path/to/my.cnf',
    
  524.             },
    
  525.         }
    
  526.     }
    
  527. 
    
  528. 
    
  529.     # my.cnf
    
  530.     [client]
    
  531.     database = NAME
    
  532.     user = USER
    
  533.     password = PASSWORD
    
  534.     default-character-set = utf8
    
  535. 
    
  536. Several other `MySQLdb connection options`_ may be useful, such as ``ssl``,
    
  537. ``init_command``, and ``sql_mode``.
    
  538. 
    
  539. .. _MySQL option file: https://dev.mysql.com/doc/refman/en/option-files.html
    
  540. .. _MySQLdb connection options: https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes
    
  541. 
    
  542. .. _mysql-sql-mode:
    
  543. 
    
  544. Setting ``sql_mode``
    
  545. ~~~~~~~~~~~~~~~~~~~~
    
  546. 
    
  547. From MySQL 5.7 onward, the default value of the ``sql_mode`` option contains
    
  548. ``STRICT_TRANS_TABLES``. That option escalates warnings into errors when data
    
  549. are truncated upon insertion, so Django highly recommends activating a
    
  550. `strict mode`_ for MySQL to prevent data loss (either ``STRICT_TRANS_TABLES``
    
  551. or ``STRICT_ALL_TABLES``).
    
  552. 
    
  553. .. _strict mode: https://dev.mysql.com/doc/refman/en/sql-mode.html#sql-mode-strict
    
  554. 
    
  555. If you need to customize the SQL mode, you can set the ``sql_mode`` variable
    
  556. like other MySQL options: either in a config file or with the entry
    
  557. ``'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"`` in the
    
  558. :setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`.
    
  559. 
    
  560. .. _mysql-isolation-level:
    
  561. 
    
  562. Isolation level
    
  563. ~~~~~~~~~~~~~~~
    
  564. 
    
  565. When running concurrent loads, database transactions from different sessions
    
  566. (say, separate threads handling different requests) may interact with each
    
  567. other. These interactions are affected by each session's `transaction isolation
    
  568. level`_. You can set a connection's isolation level with an
    
  569. ``'isolation_level'`` entry in the :setting:`OPTIONS` part of your database
    
  570. configuration in :setting:`DATABASES`. Valid values for
    
  571. this entry are the four standard isolation levels:
    
  572. 
    
  573. * ``'read uncommitted'``
    
  574. * ``'read committed'``
    
  575. * ``'repeatable read'``
    
  576. * ``'serializable'``
    
  577. 
    
  578. or ``None`` to use the server's configured isolation level. However, Django
    
  579. works best with and defaults to read committed rather than MySQL's default,
    
  580. repeatable read. Data loss is possible with repeatable read. In particular,
    
  581. you may see cases where :meth:`~django.db.models.query.QuerySet.get_or_create`
    
  582. will raise an :exc:`~django.db.IntegrityError` but the object won't appear in
    
  583. a subsequent :meth:`~django.db.models.query.QuerySet.get` call.
    
  584. 
    
  585. .. _transaction isolation level: https://dev.mysql.com/doc/refman/en/innodb-transaction-isolation-levels.html
    
  586. 
    
  587. Creating your tables
    
  588. --------------------
    
  589. 
    
  590. When Django generates the schema, it doesn't specify a storage engine, so
    
  591. tables will be created with whatever default storage engine your database
    
  592. server is configured for. The easiest solution is to set your database server's
    
  593. default storage engine to the desired engine.
    
  594. 
    
  595. If you're using a hosting service and can't change your server's default
    
  596. storage engine, you have a couple of options.
    
  597. 
    
  598. * After the tables are created, execute an ``ALTER TABLE`` statement to
    
  599.   convert a table to a new storage engine (such as InnoDB)::
    
  600. 
    
  601.       ALTER TABLE <tablename> ENGINE=INNODB;
    
  602. 
    
  603.   This can be tedious if you have a lot of tables.
    
  604. 
    
  605. * Another option is to use the ``init_command`` option for MySQLdb prior to
    
  606.   creating your tables::
    
  607. 
    
  608.       'OPTIONS': {
    
  609.          'init_command': 'SET default_storage_engine=INNODB',
    
  610.       }
    
  611. 
    
  612.   This sets the default storage engine upon connecting to the database.
    
  613.   After your tables have been created, you should remove this option as it
    
  614.   adds a query that is only needed during table creation to each database
    
  615.   connection.
    
  616. 
    
  617. Table names
    
  618. -----------
    
  619. 
    
  620. There are `known issues`_ in even the latest versions of MySQL that can cause the
    
  621. case of a table name to be altered when certain SQL statements are executed
    
  622. under certain conditions. It is recommended that you use lowercase table
    
  623. names, if possible, to avoid any problems that might arise from this behavior.
    
  624. Django uses lowercase table names when it auto-generates table names from
    
  625. models, so this is mainly a consideration if you are overriding the table name
    
  626. via the :class:`~django.db.models.Options.db_table` parameter.
    
  627. 
    
  628. .. _known issues: https://bugs.mysql.com/bug.php?id=48875
    
  629. 
    
  630. Savepoints
    
  631. ----------
    
  632. 
    
  633. Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
    
  634. <mysql-storage-engines>`) support database :ref:`savepoints
    
  635. <topics-db-transactions-savepoints>`.
    
  636. 
    
  637. If you use the MyISAM storage engine please be aware of the fact that you will
    
  638. receive database-generated errors if you try to use the :ref:`savepoint-related
    
  639. methods of the transactions API <topics-db-transactions-savepoints>`. The reason
    
  640. for this is that detecting the storage engine of a MySQL database/table is an
    
  641. expensive operation so it was decided it isn't worth to dynamically convert
    
  642. these methods in no-op's based in the results of such detection.
    
  643. 
    
  644. Notes on specific fields
    
  645. ------------------------
    
  646. 
    
  647. .. _mysql-character-fields:
    
  648. 
    
  649. Character fields
    
  650. ~~~~~~~~~~~~~~~~
    
  651. 
    
  652. Any fields that are stored with ``VARCHAR`` column types may have their
    
  653. ``max_length`` restricted to 255 characters if you are using ``unique=True``
    
  654. for the field. This affects :class:`~django.db.models.CharField`,
    
  655. :class:`~django.db.models.SlugField`. See `the MySQL documentation`_ for more
    
  656. details.
    
  657. 
    
  658. .. _the MySQL documentation: https://dev.mysql.com/doc/refman/en/create-index.html#create-index-column-prefixes
    
  659. 
    
  660. ``TextField`` limitations
    
  661. ~~~~~~~~~~~~~~~~~~~~~~~~~
    
  662. 
    
  663. MySQL can index only the first N chars of a ``BLOB`` or ``TEXT`` column. Since
    
  664. ``TextField`` doesn't have a defined length, you can't mark it as
    
  665. ``unique=True``. MySQL will report: "BLOB/TEXT column '<db_column>' used in key
    
  666. specification without a key length".
    
  667. 
    
  668. .. _mysql-fractional-seconds:
    
  669. 
    
  670. Fractional seconds support for Time and DateTime fields
    
  671. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  672. 
    
  673. MySQL can store fractional seconds, provided that the column definition
    
  674. includes a fractional indication (e.g. ``DATETIME(6)``).
    
  675. 
    
  676. Django will not upgrade existing columns to include fractional seconds if the
    
  677. database server supports it. If you want to enable them on an existing database,
    
  678. it's up to you to either manually update the column on the target database, by
    
  679. executing a command like::
    
  680. 
    
  681.     ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)
    
  682. 
    
  683. or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
    
  684. :ref:`data migration <data-migrations>`.
    
  685. 
    
  686. ``TIMESTAMP`` columns
    
  687. ~~~~~~~~~~~~~~~~~~~~~
    
  688. 
    
  689. If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
    
  690. set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
    
  691. :djadmin:`inspectdb` maps these columns to
    
  692. :class:`~django.db.models.DateTimeField` and if you enable timezone support,
    
  693. both MySQL and Django will attempt to convert the values from UTC to local time.
    
  694. 
    
  695. Row locking with ``QuerySet.select_for_update()``
    
  696. -------------------------------------------------
    
  697. 
    
  698. MySQL and MariaDB do not support some options to the ``SELECT ... FOR UPDATE``
    
  699. statement. If ``select_for_update()`` is used with an unsupported option, then
    
  700. a :exc:`~django.db.NotSupportedError` is raised.
    
  701. 
    
  702. =============== ========= ==========
    
  703. Option          MariaDB   MySQL
    
  704. =============== ========= ==========
    
  705. ``SKIP LOCKED`` X (≥10.6) X (≥8.0.1)
    
  706. ``NOWAIT``      X         X (≥8.0.1)
    
  707. ``OF``                    X (≥8.0.1)
    
  708. ``NO KEY``
    
  709. =============== ========= ==========
    
  710. 
    
  711. When using ``select_for_update()`` on MySQL, make sure you filter a queryset
    
  712. against at least a set of fields contained in unique constraints or only
    
  713. against fields covered by indexes. Otherwise, an exclusive write lock will be
    
  714. acquired over the full table for the duration of the transaction.
    
  715. 
    
  716. Automatic typecasting can cause unexpected results
    
  717. --------------------------------------------------
    
  718. 
    
  719. When performing a query on a string type, but with an integer value, MySQL will
    
  720. coerce the types of all values in the table to an integer before performing the
    
  721. comparison. If your table contains the values ``'abc'``, ``'def'`` and you
    
  722. query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
    
  723. will match the value ``'abc1'``. Therefore, string type fields included in Django
    
  724. will always cast the value to a string before using it in a query.
    
  725. 
    
  726. If you implement custom model fields that inherit from
    
  727. :class:`~django.db.models.Field` directly, are overriding
    
  728. :meth:`~django.db.models.Field.get_prep_value`, or use
    
  729. :class:`~django.db.models.expressions.RawSQL`,
    
  730. :meth:`~django.db.models.query.QuerySet.extra`, or
    
  731. :meth:`~django.db.models.Manager.raw`, you should ensure that you perform
    
  732. appropriate typecasting.
    
  733. 
    
  734. .. _sqlite-notes:
    
  735. 
    
  736. SQLite notes
    
  737. ============
    
  738. 
    
  739. Django supports SQLite 3.9.0 and later.
    
  740. 
    
  741. SQLite_ provides an excellent development alternative for applications that
    
  742. are predominantly read-only or require a smaller installation footprint. As
    
  743. with all database servers, though, there are some differences that are
    
  744. specific to SQLite that you should be aware of.
    
  745. 
    
  746. .. _SQLite: https://www.sqlite.org/
    
  747. 
    
  748. .. _sqlite-string-matching:
    
  749. 
    
  750. Substring matching and case sensitivity
    
  751. ---------------------------------------
    
  752. 
    
  753. For all SQLite versions, there is some slightly counter-intuitive behavior when
    
  754. attempting to match some types of strings.  These are triggered when using the
    
  755. :lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior
    
  756. splits into two cases:
    
  757. 
    
  758. 1. For substring matching, all matches are done case-insensitively. That is a
    
  759. filter such as ``filter(name__contains="aa")`` will match a name of ``"Aabb"``.
    
  760. 
    
  761. 2. For strings containing characters outside the ASCII range, all exact string
    
  762. matches are performed case-sensitively, even when the case-insensitive options
    
  763. are passed into the query. So the :lookup:`iexact` filter will behave exactly
    
  764. the same as the :lookup:`exact` filter in these cases.
    
  765. 
    
  766. Some possible workarounds for this are `documented at sqlite.org`_, but they
    
  767. aren't utilized by the default SQLite backend in Django, as incorporating them
    
  768. would be fairly difficult to do robustly. Thus, Django exposes the default
    
  769. SQLite behavior and you should be aware of this when doing case-insensitive or
    
  770. substring filtering.
    
  771. 
    
  772. .. _documented at sqlite.org: https://www.sqlite.org/faq.html#q18
    
  773. 
    
  774. .. _sqlite-decimal-handling:
    
  775. 
    
  776. Decimal handling
    
  777. ----------------
    
  778. 
    
  779. SQLite has no real decimal internal type. Decimal values are internally
    
  780. converted to the ``REAL`` data type (8-byte IEEE floating point number), as
    
  781. explained in the `SQLite datatypes documentation`__, so they don't support
    
  782. correctly-rounded decimal floating point arithmetic.
    
  783. 
    
  784. __ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes
    
  785. 
    
  786. "Database is locked" errors
    
  787. ---------------------------
    
  788. 
    
  789. SQLite is meant to be a lightweight database, and thus can't support a high
    
  790. level of concurrency. ``OperationalError: database is locked`` errors indicate
    
  791. that your application is experiencing more concurrency than ``sqlite`` can
    
  792. handle in default configuration. This error means that one thread or process has
    
  793. an exclusive lock on the database connection and another thread timed out
    
  794. waiting for the lock the be released.
    
  795. 
    
  796. Python's SQLite wrapper has
    
  797. a default timeout value that determines how long the second thread is allowed to
    
  798. wait on the lock before it times out and raises the ``OperationalError: database
    
  799. is locked`` error.
    
  800. 
    
  801. If you're getting this error, you can solve it by:
    
  802. 
    
  803. * Switching to another database backend. At a certain point SQLite becomes
    
  804.   too "lite" for real-world applications, and these sorts of concurrency
    
  805.   errors indicate you've reached that point.
    
  806. 
    
  807. * Rewriting your code to reduce concurrency and ensure that database
    
  808.   transactions are short-lived.
    
  809. 
    
  810. * Increase the default timeout value by setting the ``timeout`` database
    
  811.   option::
    
  812. 
    
  813.       'OPTIONS': {
    
  814.           # ...
    
  815.           'timeout': 20,
    
  816.           # ...
    
  817.       }
    
  818. 
    
  819.   This will make SQLite wait a bit longer before throwing "database is locked"
    
  820.   errors; it won't really do anything to solve them.
    
  821. 
    
  822. ``QuerySet.select_for_update()`` not supported
    
  823. ----------------------------------------------
    
  824. 
    
  825. SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
    
  826. have no effect.
    
  827. 
    
  828. "pyformat" parameter style in raw queries not supported
    
  829. -------------------------------------------------------
    
  830. 
    
  831. For most backends, raw queries (``Manager.raw()`` or ``cursor.execute()``)
    
  832. can use the "pyformat" parameter style, where placeholders in the query
    
  833. are given as ``'%(name)s'`` and the parameters are passed as a dictionary
    
  834. rather than a list. SQLite does not support this.
    
  835. 
    
  836. .. _sqlite-isolation:
    
  837. 
    
  838. Isolation when using ``QuerySet.iterator()``
    
  839. --------------------------------------------
    
  840. 
    
  841. There are special considerations described in `Isolation In SQLite`_ when
    
  842. modifying a table while iterating over it using :meth:`.QuerySet.iterator`. If
    
  843. a row is added, changed, or deleted within the loop, then that row may or may
    
  844. not appear, or may appear twice, in subsequent results fetched from the
    
  845. iterator. Your code must handle this.
    
  846. 
    
  847. .. _`Isolation in SQLite`: https://www.sqlite.org/isolation.html
    
  848. 
    
  849. .. _sqlite-json1:
    
  850. 
    
  851. Enabling JSON1 extension on SQLite
    
  852. ----------------------------------
    
  853. 
    
  854. To use :class:`~django.db.models.JSONField` on SQLite, you need to enable the
    
  855. `JSON1 extension`_ on Python's :py:mod:`sqlite3` library. If the extension is
    
  856. not enabled on your installation, a system error (``fields.E180``) will be
    
  857. raised.
    
  858. 
    
  859. To enable the JSON1 extension you can follow the instruction on
    
  860. `the wiki page`_.
    
  861. 
    
  862. .. _JSON1 extension: https://www.sqlite.org/json1.html
    
  863. .. _the wiki page: https://code.djangoproject.com/wiki/JSON1Extension
    
  864. 
    
  865. .. _oracle-notes:
    
  866. 
    
  867. Oracle notes
    
  868. ============
    
  869. 
    
  870. Django supports `Oracle Database Server`_ versions 19c and higher. Version 7.0
    
  871. or higher of the `cx_Oracle`_ Python driver is required.
    
  872. 
    
  873. .. _`Oracle Database Server`: https://www.oracle.com/
    
  874. .. _`cx_Oracle`: https://oracle.github.io/python-cx_Oracle/
    
  875. 
    
  876. In order for the ``python manage.py migrate`` command to work, your Oracle
    
  877. database user must have privileges to run the following commands:
    
  878. 
    
  879. * CREATE TABLE
    
  880. * CREATE SEQUENCE
    
  881. * CREATE PROCEDURE
    
  882. * CREATE TRIGGER
    
  883. 
    
  884. To run a project's test suite, the user usually needs these *additional*
    
  885. privileges:
    
  886. 
    
  887. * CREATE USER
    
  888. * ALTER USER
    
  889. * DROP USER
    
  890. * CREATE TABLESPACE
    
  891. * DROP TABLESPACE
    
  892. * CREATE SESSION WITH ADMIN OPTION
    
  893. * CREATE TABLE WITH ADMIN OPTION
    
  894. * CREATE SEQUENCE WITH ADMIN OPTION
    
  895. * CREATE PROCEDURE WITH ADMIN OPTION
    
  896. * CREATE TRIGGER WITH ADMIN OPTION
    
  897. 
    
  898. While the ``RESOURCE`` role has the required ``CREATE TABLE``,
    
  899. ``CREATE SEQUENCE``, ``CREATE PROCEDURE``, and ``CREATE TRIGGER`` privileges,
    
  900. and a user granted ``RESOURCE WITH ADMIN OPTION`` can grant ``RESOURCE``, such
    
  901. a user cannot grant the individual privileges (e.g. ``CREATE TABLE``), and thus
    
  902. ``RESOURCE WITH ADMIN OPTION`` is not usually sufficient for running tests.
    
  903. 
    
  904. Some test suites also create views or materialized views; to run these, the
    
  905. user also needs ``CREATE VIEW WITH ADMIN OPTION`` and
    
  906. ``CREATE MATERIALIZED VIEW WITH ADMIN OPTION`` privileges. In particular, this
    
  907. is needed for Django's own test suite.
    
  908. 
    
  909. All of these privileges are included in the DBA role, which is appropriate
    
  910. for use on a private developer's database.
    
  911. 
    
  912. The Oracle database backend uses the ``SYS.DBMS_LOB`` and ``SYS.DBMS_RANDOM``
    
  913. packages, so your user will require execute permissions on it. It's normally
    
  914. accessible to all users by default, but in case it is not, you'll need to grant
    
  915. permissions like so:
    
  916. 
    
  917. .. code-block:: sql
    
  918. 
    
  919.     GRANT EXECUTE ON SYS.DBMS_LOB TO user;
    
  920.     GRANT EXECUTE ON SYS.DBMS_RANDOM TO user;
    
  921. 
    
  922. Connecting to the database
    
  923. --------------------------
    
  924. 
    
  925. To connect using the service name of your Oracle database, your ``settings.py``
    
  926. file should look something like this::
    
  927. 
    
  928.     DATABASES = {
    
  929.         'default': {
    
  930.             'ENGINE': 'django.db.backends.oracle',
    
  931.             'NAME': 'xe',
    
  932.             'USER': 'a_user',
    
  933.             'PASSWORD': 'a_password',
    
  934.             'HOST': '',
    
  935.             'PORT': '',
    
  936.         }
    
  937.     }
    
  938. 
    
  939. 
    
  940. In this case, you should leave both :setting:`HOST` and :setting:`PORT` empty.
    
  941. However, if you don't use a ``tnsnames.ora`` file or a similar naming method
    
  942. and want to connect using the SID ("xe" in this example), then fill in both
    
  943. :setting:`HOST` and :setting:`PORT` like so::
    
  944. 
    
  945.     DATABASES = {
    
  946.         'default': {
    
  947.             'ENGINE': 'django.db.backends.oracle',
    
  948.             'NAME': 'xe',
    
  949.             'USER': 'a_user',
    
  950.             'PASSWORD': 'a_password',
    
  951.             'HOST': 'dbprod01ned.mycompany.com',
    
  952.             'PORT': '1540',
    
  953.         }
    
  954.     }
    
  955. 
    
  956. You should either supply both :setting:`HOST` and :setting:`PORT`, or leave
    
  957. both as empty strings. Django will use a different connect descriptor depending
    
  958. on that choice.
    
  959. 
    
  960. Full DSN and Easy Connect
    
  961. ~~~~~~~~~~~~~~~~~~~~~~~~~
    
  962. 
    
  963. A Full DSN or Easy Connect string can be used in :setting:`NAME` if both
    
  964. :setting:`HOST` and :setting:`PORT` are empty. This format is required when
    
  965. using RAC or pluggable databases without ``tnsnames.ora``, for example.
    
  966. 
    
  967. Example of an Easy Connect string::
    
  968. 
    
  969.     'NAME': 'localhost:1521/orclpdb1',
    
  970. 
    
  971. Example of a full DSN string::
    
  972. 
    
  973.     'NAME': (
    
  974.         '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))'
    
  975.         '(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))'
    
  976.     ),
    
  977. 
    
  978. Threaded option
    
  979. ---------------
    
  980. 
    
  981. If you plan to run Django in a multithreaded environment (e.g. Apache using the
    
  982. default MPM module on any modern operating system), then you **must** set
    
  983. the ``threaded`` option of your Oracle database configuration to ``True``::
    
  984. 
    
  985.     'OPTIONS': {
    
  986.         'threaded': True,
    
  987.     },
    
  988. 
    
  989. Failure to do this may result in crashes and other odd behavior.
    
  990. 
    
  991. INSERT ... RETURNING INTO
    
  992. -------------------------
    
  993. 
    
  994. By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
    
  995. retrieve the value of an ``AutoField`` when inserting new rows.  This behavior
    
  996. may result in a ``DatabaseError`` in certain unusual setups, such as when
    
  997. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
    
  998. The ``RETURNING INTO`` clause can be disabled by setting the
    
  999. ``use_returning_into`` option of the database configuration to ``False``::
    
  1000. 
    
  1001.     'OPTIONS': {
    
  1002.         'use_returning_into': False,
    
  1003.     },
    
  1004. 
    
  1005. In this case, the Oracle backend will use a separate ``SELECT`` query to
    
  1006. retrieve ``AutoField`` values.
    
  1007. 
    
  1008. Naming issues
    
  1009. -------------
    
  1010. 
    
  1011. Oracle imposes a name length limit of 30 characters. To accommodate this, the
    
  1012. backend truncates database identifiers to fit, replacing the final four
    
  1013. characters of the truncated name with a repeatable MD5 hash value.
    
  1014. Additionally, the backend turns database identifiers to all-uppercase.
    
  1015. 
    
  1016. To prevent these transformations (this is usually required only when dealing
    
  1017. with legacy databases or accessing tables which belong to other users), use
    
  1018. a quoted name as the value for ``db_table``::
    
  1019. 
    
  1020.     class LegacyModel(models.Model):
    
  1021.         class Meta:
    
  1022.             db_table = '"name_left_in_lowercase"'
    
  1023. 
    
  1024.     class ForeignModel(models.Model):
    
  1025.         class Meta:
    
  1026.             db_table = '"OTHER_USER"."NAME_ONLY_SEEMS_OVER_30"'
    
  1027. 
    
  1028. Quoted names can also be used with Django's other supported database
    
  1029. backends; except for Oracle, however, the quotes have no effect.
    
  1030. 
    
  1031. When running ``migrate``, an ``ORA-06552`` error may be encountered if
    
  1032. certain Oracle keywords are used as the name of a model field or the
    
  1033. value of a ``db_column`` option.  Django quotes all identifiers used
    
  1034. in queries to prevent most such problems, but this error can still
    
  1035. occur when an Oracle datatype is used as a column name.  In
    
  1036. particular, take care to avoid using the names ``date``,
    
  1037. ``timestamp``, ``number`` or ``float`` as a field name.
    
  1038. 
    
  1039. .. _oracle-null-empty-strings:
    
  1040. 
    
  1041. NULL and empty strings
    
  1042. ----------------------
    
  1043. 
    
  1044. Django generally prefers to use the empty string (``''``) rather than
    
  1045. ``NULL``, but Oracle treats both identically. To get around this, the
    
  1046. Oracle backend ignores an explicit ``null`` option on fields that
    
  1047. have the empty string as a possible value and generates DDL as if
    
  1048. ``null=True``. When fetching from the database, it is assumed that
    
  1049. a ``NULL`` value in one of these fields really means the empty
    
  1050. string, and the data is silently converted to reflect this assumption.
    
  1051. 
    
  1052. ``TextField`` limitations
    
  1053. -------------------------
    
  1054. 
    
  1055. The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
    
  1056. some limitations on the usage of such LOB columns in general:
    
  1057. 
    
  1058. * LOB columns may not be used as primary keys.
    
  1059. 
    
  1060. * LOB columns may not be used in indexes.
    
  1061. 
    
  1062. * LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
    
  1063.   attempting to use the ``QuerySet.distinct`` method on a model that
    
  1064.   includes ``TextField`` columns will result in an ``ORA-00932`` error when
    
  1065.   run against Oracle. As a workaround, use the ``QuerySet.defer`` method in
    
  1066.   conjunction with ``distinct()`` to prevent ``TextField`` columns from being
    
  1067.   included in the ``SELECT DISTINCT`` list.
    
  1068. 
    
  1069. .. _subclassing-database-backends:
    
  1070. 
    
  1071. Subclassing the built-in database backends
    
  1072. ==========================================
    
  1073. 
    
  1074. Django comes with built-in database backends. You may subclass an existing
    
  1075. database backends to modify its behavior, features, or configuration.
    
  1076. 
    
  1077. Consider, for example, that you need to change a single database feature.
    
  1078. First, you have to create a new directory with a ``base`` module in it. For
    
  1079. example::
    
  1080. 
    
  1081.     mysite/
    
  1082.         ...
    
  1083.         mydbengine/
    
  1084.             __init__.py
    
  1085.             base.py
    
  1086. 
    
  1087. The ``base.py`` module must contain a class named ``DatabaseWrapper`` that
    
  1088. subclasses an existing engine from the ``django.db.backends`` module. Here's an
    
  1089. example of subclassing the PostgreSQL engine to change a feature class
    
  1090. ``allows_group_by_selected_pks_on_model``:
    
  1091. 
    
  1092. .. code-block:: python
    
  1093.     :caption: ``mysite/mydbengine/base.py``
    
  1094. 
    
  1095.     from django.db.backends.postgresql import base, features
    
  1096. 
    
  1097.     class DatabaseFeatures(features.DatabaseFeatures):
    
  1098.         def allows_group_by_selected_pks_on_model(self, model):
    
  1099.             return True
    
  1100. 
    
  1101.     class DatabaseWrapper(base.DatabaseWrapper):
    
  1102.         features_class = DatabaseFeatures
    
  1103. 
    
  1104. Finally, you must specify a :setting:`DATABASE-ENGINE` in your ``settings.py``
    
  1105. file::
    
  1106. 
    
  1107.     DATABASES = {
    
  1108.         'default': {
    
  1109.             'ENGINE': 'mydbengine',
    
  1110.             ...
    
  1111.         },
    
  1112.     }
    
  1113. 
    
  1114. You can see the current list of database engines by looking in
    
  1115. :source:`django/db/backends`.
    
  1116. 
    
  1117. .. _third-party-notes:
    
  1118. 
    
  1119. Using a 3rd-party database backend
    
  1120. ==================================
    
  1121. 
    
  1122. In addition to the officially supported databases, there are backends provided
    
  1123. by 3rd parties that allow you to use other databases with Django:
    
  1124. 
    
  1125. * `CockroachDB`_
    
  1126. * `Firebird`_
    
  1127. * `Google Cloud Spanner`_
    
  1128. * `Microsoft SQL Server`_
    
  1129. * `TiDB`_
    
  1130. * `YugabyteDB`_
    
  1131. 
    
  1132. The Django versions and ORM features supported by these unofficial backends
    
  1133. vary considerably. Queries regarding the specific capabilities of these
    
  1134. unofficial backends, along with any support queries, should be directed to
    
  1135. the support channels provided by each 3rd party project.
    
  1136. 
    
  1137. .. _CockroachDB: https://pypi.org/project/django-cockroachdb/
    
  1138. .. _Firebird: https://pypi.org/project/django-firebird/
    
  1139. .. _Google Cloud Spanner: https://pypi.org/project/django-google-spanner/
    
  1140. .. _Microsoft SQL Server: https://pypi.org/project/mssql-django/
    
  1141. .. _TiDB: https://pypi.org/project/django-tidb/
    
  1142. .. _YugabyteDB: https://pypi.org/project/django-yugabytedb/