databases.txt 47 KB

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