2
0

databases.txt 47 KB

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