{"id":16417454,"url":"https://github.com/microsoft/mssql-django","last_synced_at":"2025-10-26T20:30:37.569Z","repository":{"id":37073319,"uuid":"305859005","full_name":"microsoft/mssql-django","owner":"microsoft","description":"The Microsoft Django backend for SQL Server provides a connectivity layer for Django on SQL Server or Azure SQL DB.","archived":false,"fork":false,"pushed_at":"2024-09-26T18:54:36.000Z","size":1221,"stargazers_count":357,"open_issues_count":66,"forks_count":120,"subscribers_count":24,"default_branch":"dev","last_synced_at":"2025-02-07T17:16:54.708Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microsoft.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":"SUPPORT.md","governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-20T23:43:05.000Z","updated_at":"2025-02-06T18:26:48.000Z","dependencies_parsed_at":"2022-07-21T21:47:43.017Z","dependency_job_id":"e3a5c328-709c-4846-b289-0828919e1349","html_url":"https://github.com/microsoft/mssql-django","commit_stats":{"total_commits":622,"total_committers":53,"mean_commits":"11.735849056603774","dds":0.635048231511254,"last_synced_commit":"d07417217065ef2539c8b2a8afb81f762086e09c"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fmssql-django","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fmssql-django/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fmssql-django/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fmssql-django/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microsoft","download_url":"https://codeload.github.com/microsoft/mssql-django/tar.gz/refs/heads/dev","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238394323,"owners_count":19464583,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-11T07:11:31.166Z","updated_at":"2025-10-26T20:30:37.563Z","avatar_url":"https://github.com/microsoft.png","language":"Python","readme":"# Microsoft Django backend for SQL Server\n\nWelcome to the MSSQL-Django 3rd party backend project!\n\n*mssql-django* is a fork of [django-mssql-backend](https://pypi.org/project/django-mssql-backend/). This project provides an enterprise database connectivity option for the Django Web Framework, with support for Microsoft SQL Server and Azure SQL Database.\n\nWe'd like to give thanks to the community that made this project possible, with particular recognition of the contributors: OskarPersson, michiya, dlo and the original Google Code django-pyodbc team. Moving forward we encourage partipation in this project from both old and new contributors!\n\nWe hope you enjoy using the MSSQL-Django 3rd party backend.\n\n## Features\n\n-  Supports Django 3.2, 4.0, 4.1, 4.2, 5.0, 5.1, and 5.2\n   - **Django 5.0 and below**: Full production support\n   - **Django 5.1**: Supported with minor limitations (composite primary key inspectdb)\n   - **Django 5.2**: Supported with enhanced SQL Server compatibility features and documented limitations (see Django 5.2 Specific Limitations section below)\n-  Tested on Microsoft SQL Server 2016, 2017, 2019, 2022\n-  Passes most of the tests of the Django test suite\n-  Enhanced SQL Server compatibility with automatic schema creation and improved identifier quoting\n-  Compatible with\n   [Micosoft ODBC Driver for SQL Server](https://docs.microsoft.com/en-us/sql/connect/odbc/microsoft-odbc-driver-for-sql-server),\n   [SQL Server Native Client](https://msdn.microsoft.com/en-us/library/ms131321(v=sql.120).aspx),\n   and [FreeTDS](https://www.freetds.org/) ODBC drivers\n\n## Dependencies\n\n-  pyodbc 3.0 or newer\n\n## Installation\n\n1. Install pyodbc 3.0 (or newer) and Django\n2. Install mssql-django:\n\n       pip install mssql-django\n\n3. Set the `ENGINE` setting in the `settings.py` file used by\n   your Django application or project to `'mssql'`:\n\n       'ENGINE': 'mssql'\n\n## Configuration\n\n### Standard Django settings\n\nThe following entries in a database-level settings dictionary\nin DATABASES control the behavior of the backend:\n\n-  ENGINE\n\n   String. It must be `\"mssql\"`.\n\n-  NAME\n\n   String. Database name. Required.\n\n-  HOST\n\n   String. SQL Server instance in `\"server\\instance\"` format.\n\n-  PORT\n\n   String. Server instance port.\n   An empty string means the default port.\n\n-  USER\n\n   String. Database user name in `\"user\"` format.\n   If not given then MS Integrated Security will be used.\n\n-  PASSWORD\n\n   String. Database user password.\n\n-  TOKEN\n\n   String. Access token fetched as a user or service principal which\n   has access to the database. E.g. when using `azure.identity`, the\n   result of `DefaultAzureCredential().get_token('https://database.windows.net/.default')`\n   can be passed.\n\n-  AUTOCOMMIT\n\n   Boolean. Set this to `False` if you want to disable\n   Django's transaction management and implement your own.\n\n-  Trusted_Connection\n\n   String. Default is `\"yes\"`. Can be set to `\"no\"` if required.\n\nand the following entries are also available in the `TEST` dictionary\nfor any given database-level settings dictionary:\n\n-  NAME\n\n   String. The name of database to use when running the test suite.\n   If the default value (`None`) is used, the test database will use\n   the name `\"test_\" + NAME`.\n\n-  COLLATION\n\n   String. The collation order to use when creating the test database.\n   If the default value (`None`) is used, the test database is assigned\n   the default collation of the instance of SQL Server.\n\n-  DEPENDENCIES\n\n   String. The creation-order dependencies of the database.\n   See the official Django documentation for more details.\n\n-  MIRROR\n\n   String. The alias of the database that this database should\n   mirror during testing. Default value is `None`.\n   See the official Django documentation for more details.\n\n### OPTIONS\n\nDictionary. Current available keys are:\n\n-  driver\n\n   String. ODBC Driver to use (`\"ODBC Driver 17 for SQL Server\"`,\n   `\"SQL Server Native Client 11.0\"`, `\"FreeTDS\"` etc).\n   Default is `\"ODBC Driver 17 for SQL Server\"`.\n\n-  isolation_level\n\n   String. Sets [transaction isolation level](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql)\n   for each database session. Valid values for this entry are\n   `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`,\n   `SNAPSHOT`, and `SERIALIZABLE`. Default is `None` which means\n   no isolation level is set to a database session and SQL Server default\n   will be used.\n\n-  dsn\n\n   String. A named DSN can be used instead of `HOST`.\n\n-  host_is_server\n\n   Boolean. Only relevant if using the FreeTDS ODBC driver under\n   Unix/Linux.\n\n   By default, when using the FreeTDS ODBC driver the value specified in\n   the ``HOST`` setting is used in a ``SERVERNAME`` ODBC connection\n   string component instead of being used in a ``SERVER`` component;\n   this means that this value should be the name of a *dataserver*\n   definition present in the ``freetds.conf`` FreeTDS configuration file\n   instead of a hostname or an IP address.\n\n   But if this option is present and its value is ``True``, this\n   special behavior is turned off. Instead, connections to the database\n   server will be established using ``HOST`` and ``PORT`` options, without\n   requiring ``freetds.conf`` to be configured.\n\n   See https://www.freetds.org/userguide/dsnless.html for more information.\n\n-  unicode_results\n\n   Boolean. If it is set to ``True``, pyodbc's *unicode_results* feature\n   is activated and strings returned from pyodbc are always Unicode.\n   Default value is ``False``.\n\n-  extra_params\n\n   String. Additional parameters for the ODBC connection. The format is\n   ``\"param=value;param=value\"``, [Azure AD Authentication](https://github.com/microsoft/mssql-django/wiki/Azure-AD-Authentication) (Service Principal, Interactive, Msi) can be added to this field.\n\n-  collation\n\n   String. Name of the collation to use when performing text field\n   lookups against the database. Default is ``None``; this means no\n   collation specifier is added to your lookup SQL (the default\n   collation of your database will be used). For Chinese language you\n   can set it to ``\"Chinese_PRC_CI_AS\"``.\n\n-  connection_timeout\n\n   Integer. Sets the timeout in seconds for the database connection process.\n   Default value is ``0`` which disables the timeout.\n\n-  connection_retries\n\n   Integer. Sets the times to retry the database connection process.\n   Default value is ``5``.\n\n-  connection_retry_backoff_time\n\n   Integer. Sets the back off time in seconds for reries of\n   the database connection process. Default value is ``5``.\n\n-  query_timeout\n\n   Integer. Sets the timeout in seconds for the database query.\n   Default value is ``0`` which disables the timeout.\n\n- [setencoding](https://github.com/mkleehammer/pyodbc/wiki/Connection#setencoding) and [setdecoding](https://github.com/mkleehammer/pyodbc/wiki/Connection#setdecoding)\n\n    ```python\n    # Example\n    \"OPTIONS\": {\n            \"setdecoding\": [\n                {\"sqltype\": pyodbc.SQL_CHAR, \"encoding\": 'utf-8'},\n                {\"sqltype\": pyodbc.SQL_WCHAR, \"encoding\": 'utf-8'}],\n            \"setencoding\": [\n                {\"encoding\": \"utf-8\"}],\n            ...\n            },\n    ```\n\n- return_rows_bulk_insert\n\n  Boolean. Sets if backend can return rows from bulk insert.\n  Default value is False which doesn't allows for the backend to\n  return rows from bulk insert. Must be set to False if database\n  has tables with triggers to prevent errors when inserting.\n\n  ```python\n  # Examples\n  \"OPTIONS\": {\n      # This database doesn't have any triggers so can use return\n      # rows from bulk insert feature\n      \"return_rows_bulk_insert\": True\n  }\n\n  \"OPTIONS\": {\n      # This database has triggers so leave return_rows_bulk_insert as blank (False)\n      # to prevent errors related to inserting and returning rows from bulk insert\n  }\n  ```\n\n### Backend-specific settings\n\nThe following project-level settings also control the behavior of the backend:\n\n-  DATABASE_CONNECTION_POOLING\n\n   Boolean. If it is set to ``False``, pyodbc's connection pooling feature\n   won't be activated.\n\n### Example\n\nHere is an example of the database settings:\n\n```python\n    DATABASES = {\n        'default': {\n            'ENGINE': 'mssql',\n            'NAME': 'mydb',\n            'USER': 'user@myserver',\n            'PASSWORD': 'password',\n            'HOST': 'myserver.database.windows.net',\n            'PORT': '',\n\n            'OPTIONS': {\n                'driver': 'ODBC Driver 17 for SQL Server',\n            },\n        },\n    }\n\n    # set this to False if you want to turn off pyodbc's connection pooling\n    DATABASE_CONNECTION_POOLING = False\n```\n\n## Limitations\n\nThe following features are currently not fully supported:\n- Altering a model field from or to AutoField at migration\n- Django annotate functions have floating point arithmetic problems in some cases\n- Annotate function with exists\n- Exists function in order_by\n- Righthand power and arithmetic with datatimes\n- Timezones, timedeltas not fully supported\n- Rename field/model with foreign key constraint\n- Database level constraints\n- Filtered index\n- Date extract function\n- Bulk insert into a table with a trigger and returning the rows inserted\n\n### Django 5.1 Specific Limitations\n\nDjango 5.1 introduces composite primary key support which has limited compatibility with SQL Server:\n- **inspectdb command**: Cannot properly inspect tables with composite primary keys\n- **Backend debugging**: SQL execution wrapper debug functionality may not work correctly\n- **Schema operations**: Some field unique constraint removal operations may have issues\n- Most other Django 5.1 features work correctly with SQL Server\n\n### Django 5.2 Specific Limitations\n\nDjango 5.2 introduces new features that may cause regressions for existing Django 5.0+ applications. This release includes enhanced SQL Server compatibility for Django 5.2, with automatic schema creation and improved identifier quoting. The following limitations remain:\n\n**Critical Limitations (May Affect Common Use Cases):**\n- **Tuple lookups**: Queries like `Model.objects.filter((col1, col2)__in=[(val1, val2)])` will fail with SQL syntax errors as SQL Server doesn't support `(col1, col2) IN (...)` syntax\n- **Multi-column foreign key relationships**: Complex queries involving foreign keys with multiple columns may fail in Django 5.2 due to tuple lookup generation\n- **JSONField with special characters**: JSONField lookups involving special characters (quotes, emojis, escape sequences) may generate invalid SQL\n- **JSONField bulk updates**: Bulk update operations on JSONField with null handling may fail\n\n**Moderate Impact:**\n- **Complex aggregations**: Some aggregation queries with filtered references and subqueries may not work correctly\n- **Prefetch operations**: `prefetch_related()` operations on multi-column foreign keys may fail\n\n**Low Impact (Edge Cases):**\n- **Migration operations**: Advanced migration operations involving composite primary keys and generated fields\n- **Backend debugging**: Certain backend debugging and introspection features\n- **JSONField CASE WHEN updates**: JSONField updates using CASE WHEN expressions with null handling\n\n**Specific Test Failures in Django 5.2:**\n- All `foreign_object.test_tuple_lookups.TupleLookupsTests.*` tests\n- All `foreign_object.tests.MultiColumnFKTests.*` tests involving complex queries\n- `model_fields.test_jsonfield.TestQuerying.test_lookups_special_chars*` tests\n- `queries.test_bulk_update.BulkUpdateTests.test_json_field_sql_null` test\n- Various migration and backend debugging tests\n\n**Workaround**: These limitations are documented in the test exclusions (`testapp/settings.py`) and are excellent candidates for community contributions. Applications using Django 5.0 and below are unaffected by these limitations.\n\nJSONField lookups have limitations, more details [here](https://github.com/microsoft/mssql-django/wiki/JSONField).\n\n## Contributing\n\nMore details on contributing can be found [here](CONTRIBUTING.md).\n\nThis project welcomes contributions and suggestions.  Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.\n\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n## Security Reporting Instructions\n\nFor security reporting instructions please refer to the [`SECURITY.md`](SECURITY.md) file in this repository.\n\n## Trademarks\n\nThis project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft\ntrademarks or logos is subject to and must follow\n[Microsoft's Trademark \u0026 Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).\nUse of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.\nAny use of third-party trademarks or logos are subject to those third-party's policies.\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2Fmssql-django","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicrosoft%2Fmssql-django","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2Fmssql-django/lists"}