mssql-django is the official Microsoft‑supported Django database backend for SQL Server, Azure SQL and SQL Database in Microsoft Fabric.
It provides a reliable, enterprise‑grade database connectivity option for the Django web framework, enabling Python developers to build and run production‑ready applications on Microsoft’s data platform.
This project is the continuation and evolution of earlier community efforts, and it builds on the strong foundation established by django-mssql-backend and its predecessors. mssql-django focuses on long‑term stability, performance, security, and compatibility with both Django and SQL Server.
| Component | Supported Versions |
|---|---|
| Django | 5.2, 6.0, 6.1 |
| Python | CPython 3.10 – 3.14 (Django 6.0 and 6.1 require 3.12+) |
| Platforms | Windows x64; Windows ARM64 with Python 3.11+; macOS 15+ on Intel or Apple silicon; Linux x64/ARM64 with glibc 2.28+ or musl 1.2+ |
| SQL Server | 2017, 2019, 2022, 2025 |
| Azure SQL | Database, Managed Instance, SQL Database in Microsoft Fabric |
| Database driver | pyodbc (default), mssql-python |
| Native connectivity | Microsoft ODBC Driver 17/18 with pyodbc; Microsoft ODBC Driver 18 supplied by mssql-python-odbc with mssql-python |
mssql-django 2.0 requires mssql-python and therefore supports only platforms with a compatible mssql-python distribution. SUSE Linux ARM64 is not supported. Users on other platforms must remain on mssql-django 1.8.0.
-
Install mssql-django (pulls in Django, mssql-python, pyodbc, and tzdata automatically):
pip install mssql-django -
Configure your
settings.py:
DATABASES = {
'default': {
'ENGINE': 'mssql',
'NAME': 'mydb',
'USER': 'user@myserver',
'PASSWORD': 'password',
'HOST': 'myserver.database.windows.net',
'PORT': '',
},
}
# Set this to False to turn off connection pooling for both database drivers.
DATABASE_CONNECTION_POOLING = False| Setting | Type | Description |
|---|---|---|
ENGINE |
String | Must be "mssql" |
NAME |
String | Database name. Required. |
HOST |
String | SQL Server instance in "server\instance" format |
PORT |
String | Server instance port. Empty string means default port. |
USER |
String | Database user name. If not given, MS Integrated Security is used. |
PASSWORD |
String | Database user password |
TOKEN |
String | Access token for Microsoft Entra ID authentication (e.g. via azure.identity) |
AUTOCOMMIT |
Boolean | Set to False to disable Django's transaction management |
Trusted_Connection |
String | Default "yes". Set to "no" if required. |
| Setting | Type | Description |
|---|---|---|
NAME |
String | Test database name. Default: "test_" + NAME |
COLLATION |
String | Collation for test database. Default: instance default. |
DEPENDENCIES |
String | Creation-order dependencies of the database |
MIRROR |
String | Alias of database to mirror during testing |
| Option | Type | Default | Description |
|---|---|---|---|
python_driver |
String | Unset | Set to "mssql_python" per alias to opt in; unset or "pyodbc" keeps the default. See Selecting the database driver. |
driver |
String | "ODBC Driver 18 for SQL Server" |
Native driver override for pyodbc. When omitted, Driver 18 is attempted first with automatic fallback to Driver 17. Explicit values do not fall back. |
isolation_level |
String | None |
Transaction isolation level: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT, or SERIALIZABLE |
dsn |
String | Unset | Named DSN, can be used instead of HOST (pyodbc only) |
unicode_results |
Boolean | False |
Activate pyodbc's unicode_results feature |
extra_params |
String | Unset | Additional connection parameters ("param=value;param=value"), passed unchanged and validated by the selected driver. See authentication and driver-specific rules. |
collation |
String | None |
Collation for text field lookups (e.g. "Chinese_PRC_CI_AS") |
connection_timeout |
Integer | 0 |
Connection timeout in seconds (0 = disabled) |
connection_retries |
Integer | 5 |
Number of connection retry attempts |
connection_retry_backoff_time |
Integer | 5 |
Back-off time in seconds between retries |
query_timeout |
Integer | 0 |
Query timeout in seconds (0 = disabled) |
setencoding / setdecoding |
List | Unset | Forwarded to the selected connection. Each dictionary must match that driver's method signature and is not portable between drivers. mssql-python requires sqltype in each setdecoding entry. See the pyodbc encoding / decoding reference. |
return_rows_bulk_insert |
Boolean | False |
Allow returning rows from bulk insert. Must be False if tables have triggers. |
On the pyodbc path, the backend enables Multiple Active Result Sets (MARS) by
default with Microsoft ODBC drivers on Windows. To connect to an endpoint that does not support MARS,
such as Microsoft Fabric Warehouse, set MARS_Connection=no in that database
alias's extra_params:
'OPTIONS': {
'driver': 'ODBC Driver 18 for SQL Server',
'extra_params': 'Authentication=ActiveDirectoryServicePrincipal;MARS_Connection=no',
},Keep your existing HOST, NAME, USER (client ID), and PASSWORD (client
secret) settings. For other authentication methods, keep the corresponding
authentication settings and append MARS_Connection=no to extra_params.
An explicit MARS setting is honored case-insensitively, without adding a
conflicting default. With MARS disabled, ORM iteration buffers results before
yielding them so nested queries can use the same connection; this can use more
memory for large querysets. This connection setting does not imply full
Warehouse support for Django migrations or other SQL Server features.
mssql-django installs both pyodbc and
mssql-python >=1.15.0. pyodbc
remains the default. Select mssql-python per alias without changing ENGINE:
'OPTIONS': {
'python_driver': 'mssql_python',
},Omit python_driver or set it to "pyodbc" to roll back. Aliases can use
different drivers.
- Runtime. pip automatically installs the
mssql-python-odbccompanion package, which supplies Microsoft ODBC Driver 18. Private indexes and--no-depsinstallations must provide the companion package separately. Install mssql-python's platform prerequisites, including OpenSSL on macOS and the required Linux libraries. - Connections.
HOSTand optionalPORTbecomeSERVER=host,port.driver,dsn,host_is_server, andunicode_resultsare ignored; Driver 17 fallback is pyodbc-only. An emptyHOSTuseslocalhost, matching the pyodbc local-server default. - Additional parameters. mssql-python 1.15 validates
extra_paramsagainst a strict allowlist. Supported options includeAuthentication,Encrypt,TrustServerCertificate,HostnameInCertificate,ServerCertificate,ServerSPN,MultiSubnetFailover,ApplicationIntent,ConnectRetryCount,ConnectRetryInterval,KeepAlive,KeepAliveInterval,IpAddressPreference, andPacketSize. Common pyodbc-only keywords such asAPP,LongAsMax,ColumnEncryption,WSID,AnsiNPW,QuotedId,Regional,UseFMTONLY,Current Language,Network Library,Description, andConnect Timeoutare rejected, as areDRIVER,DSN,SERVERNAME, andMARS_Connection. Remove unsupported keywords before switching; use theconnection_timeoutoption instead ofConnect Timeout. Explicit supported values override generated ones. - Security and authentication. Use trusted certificates in production.
TrustServerCertificate=yesis for trusted local development only. Use a supported authentication mode inextra_params, or supplyTOKENwithoutUSER,PASSWORD, orAuthentication; the application owns token acquisition and renewal. - Iteration. mssql-python does not enable MARS. To allow nested queries on
one connection,
QuerySet.iterator()buffers the full result before yielding, regardless ofchunk_size; account for that memory on large querysets.MARS_Connection=noremains a pyodbc-only setting for endpoints covered by Disabling MARS.
| Setting | Type | Default | Description |
|---|---|---|---|
DATABASE_CONNECTION_POOLING |
Boolean | True |
Set to False before opening connections to disable driver pooling. Applies to pyodbc and mssql-python. |
The following limitations apply when using SQL Server with Django:
- Altering a model field from or to AutoField at migration
- Floating point arithmetic in some annotate functions
- Annotate/exists function in
order_by - Righthand power and arithmetic with datetimes
- Timezones and timedeltas not fully supported
- Rename field/model with foreign key constraint
- Database level constraints and filtered indexes
- Date extract function
- Bulk insert with triggers and returning rows
| Version | Notes |
|---|---|
| Django 5.2 | Tuple lookups require Django 5.2.4+ for full support. Some JSONField bulk/CASE WHEN update edge cases. See test exclusions for details. |
| Django 6.0 | Requires Python 3.12+. Backend handles the 6.0 API changes transparently. |
| Django 6.1 | Requires Python 3.12+. Database-level referential actions (DB_CASCADE, DB_SET_NULL, DB_SET_DEFAULT) are unavailable because SQL Server disallows multiple cascade paths to the same table; using one raises fields.E324. Bitwise aggregates (BitAnd, BitOr, BitXor) are not implemented and raise NotSupportedError. See test exclusions for details. |
JSONField lookups have additional limitations — see the JSONField wiki page.
| Resource | Link |
|---|---|
| Wiki & Guides | mssql-django Wiki |
| Contributing | Contributing Guide |
| Code of Conduct | Microsoft Open Source Code of Conduct |
Check the FAQ or open an issue on GitHub.
We welcome contributions and suggestions! See CONTRIBUTING.md for details.
All contributors are listed on GitHub: Contributor Insights
Most contributions require a Contributor License Agreement (CLA). For details, visit https://cla.opensource.microsoft.com. A CLA bot will guide you when you submit a pull request.
This project has adopted the Microsoft Open Source Code of Conduct.
For security reporting instructions please refer to SECURITY.md.
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.