Metadata-Version: 2.4
Name: mssql-django
Version: 2.0.0
Summary: Django backend for Microsoft SQL Server
Home-page: https://github.com/microsoft/mssql-django
Author: Microsoft
Author-email: opencode@microsoft.com
License: BSD
Project-URL: Release Notes, https://github.com/microsoft/mssql-django/releases
Keywords: django
Classifier: License :: OSI Approved :: BSD License
Classifier: Framework :: Django
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
License-File: NOTICE.md
Requires-Dist: django<6.2,>=5.2
Requires-Dist: mssql-python>=1.15.0
Requires-Dist: pyodbc>=3.0
Requires-Dist: tzdata
Provides-Extra: test
Requires-Dist: unittest-xml-reporting>=3.2.0; extra == "test"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Django Backend for Microsoft SQL

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.

## Supportability

| 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.

## Quick Start

1. Install mssql-django (pulls in Django, mssql-python, pyodbc, and tzdata automatically):

       pip install mssql-django

2. Configure your `settings.py`:

```python
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
```

## Configuration Reference

### Standard Django Settings

| 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. |

### TEST Settings

| 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 |

### OPTIONS

| 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](#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](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql): `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](https://github.com/microsoft/mssql-django/wiki/Azure-AD-Authentication) and [driver-specific rules](#selecting-the-database-driver). |
| `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](https://github.com/mkleehammer/pyodbc/wiki/Connection#setencoding) / [decoding](https://github.com/mkleehammer/pyodbc/wiki/Connection#setdecoding) reference. |
| `return_rows_bulk_insert` | Boolean | `False` | Allow returning rows from bulk insert. Must be `False` if tables have triggers. |

#### Disabling MARS

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`:

```python
'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.

### Selecting the database driver

mssql-django installs both **pyodbc** and
[mssql-python](https://github.com/microsoft/mssql-python) >=1.15.0. pyodbc
remains the default. Select mssql-python per alias without changing `ENGINE`:

```python
'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-odbc` companion
  package, which supplies Microsoft ODBC Driver 18. Private indexes and
  `--no-deps` installations must provide the companion package separately.
  Install mssql-python's [platform prerequisites](https://github.com/microsoft/mssql-python#installation),
  including OpenSSL on macOS and the required Linux libraries.
- **Connections.** `HOST` and optional `PORT` become `SERVER=host,port`.
  `driver`, `dsn`, `host_is_server`, and `unicode_results` are ignored; Driver
  17 fallback is pyodbc-only. An empty `HOST` uses `localhost`, matching the
  pyodbc local-server default.
- **Additional parameters.** mssql-python 1.15 validates `extra_params` against
  a strict allowlist. Supported options include `Authentication`, `Encrypt`,
  `TrustServerCertificate`, `HostnameInCertificate`, `ServerCertificate`,
  `ServerSPN`, `MultiSubnetFailover`, `ApplicationIntent`,
  `ConnectRetryCount`, `ConnectRetryInterval`, `KeepAlive`,
  `KeepAliveInterval`, `IpAddressPreference`, and `PacketSize`. Common
  pyodbc-only keywords such as `APP`, `LongAsMax`, `ColumnEncryption`, `WSID`,
  `AnsiNPW`, `QuotedId`, `Regional`, `UseFMTONLY`, `Current Language`,
  `Network Library`, `Description`, and `Connect Timeout` are rejected, as are
  `DRIVER`, `DSN`, `SERVERNAME`, and `MARS_Connection`. Remove unsupported
  keywords before switching; use the `connection_timeout` option instead of
  `Connect Timeout`. Explicit supported values override generated ones.
- **Security and authentication.** Use trusted certificates in production.
  `TrustServerCertificate=yes` is for trusted local development only. Use a
  [supported authentication mode](https://github.com/microsoft/mssql-python/wiki/Microsoft-Entra-ID-support)
  in `extra_params`, or supply `TOKEN` without `USER`, `PASSWORD`, or
  `Authentication`; 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 of `chunk_size`; account for that memory on large
  querysets. `MARS_Connection=no` remains a pyodbc-only setting for endpoints
  covered by [Disabling MARS](#disabling-mars).

### Backend-Specific Settings

| 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. |

## Known Limitations

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-Specific Notes

| 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](https://github.com/microsoft/mssql-django/blob/dev/testapp/settings.py) 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](https://github.com/microsoft/mssql-django/blob/dev/testapp/settings.py) for details. |

JSONField lookups have additional limitations — see the [JSONField wiki page](https://github.com/microsoft/mssql-django/wiki/JSONField).

## Helpful Links

| Resource | Link |
|---|---|
| Wiki & Guides | [mssql-django Wiki](https://github.com/microsoft/mssql-django/wiki) |
| Contributing | [Contributing Guide](https://github.com/microsoft/mssql-django/blob/dev/CONTRIBUTING.md) |
| Code of Conduct | [Microsoft Open Source Code of Conduct](https://github.com/microsoft/mssql-django/blob/dev/CODE_OF_CONDUCT.md) |

## Still have questions?

Check the [FAQ](https://github.com/microsoft/mssql-django/wiki/Frequently-Asked-Questions) or [open an issue](https://github.com/microsoft/mssql-django/issues/new) on GitHub.

## Contributing

We welcome contributions and suggestions! See [CONTRIBUTING.md](https://github.com/microsoft/mssql-django/blob/dev/CONTRIBUTING.md) for details.

All contributors are listed on GitHub: [Contributor Insights](https://github.com/microsoft/mssql-django/graphs/contributors)

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](https://opensource.microsoft.com/codeofconduct/).

## Security

For security reporting instructions please refer to [`SECURITY.md`](https://github.com/microsoft/mssql-django/blob/dev/SECURITY.md).

## Trademarks

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](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
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.
