databases.txt 46 KB

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