Connecting Django to MSSQL as the database

Django + MSSQL works really well thanks to the Microsoft sponsored mssql-django package.  The 1.0 release dates back to Jul 2021, and the current release is 1.6 from August 2025. So it looks like Microsoft is not doing their usual bait and switch where they support an open source initiative for a short time then abandon it.

To get django-mssql running:

Setup your requirements.txt

pyodbc==4.0.39
mssql-django==5.3.0

Note that I strongly prefer to use pegged versions in requirements.txt (with the =={version} part) vs just the package name which will pull the latest release and could introduce problems later.

Install it:

pip install -r requirements.txt

On MacOS I had to do these additional steps to get it working locally:

brew install unixodbc
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew install msodbcsql17 mssql-tools
pip install --no-binary :all: pyodbc

Configure your database connection in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': 'DATABASE NAME',
        'HOST': 'DATABASE HOST',
        # 'PORT': custom port if needed,   # default is 1433
        'USER': 'DB USER',
        'PASSWORD': 'DB PASSWORD,
        'AUTOCOMMIT': True,
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',     # set to "SQL Server Native Client 11.0" on Windows?
        },
    }
}

I’ve got autocommit set to true here so every SQL statement is automatically committed after it is ran.

Note – don’t store the DB username and password directly in the settings file. Use an environment variables or read from a secrets file.

For making migrations more secure, see my post on that.

From there run your migrations as normal:

python manage.py makemigrations
python manage.py migrate

 

This entry was posted in Application Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *