简体   繁体   中英

How do you connect Django to an existing Microsoft SQL Server DB stored on Azure?

I have setup a Django API connected to a React frontend. I'm attempting to connect the Django API to an already existing mssql database on Azure. It's my understanding I need to implement all the existing tables from the database into a models.py file. If that isn't the case and I can access selected tables please let me know.

I've installed pyodbc, djagno-pyodbc-azure, and mssql-django.

In my settings.py I have the data:

DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': 'DBNAME',
        'USER': 'USERNAME',
        'PASSWORD': 'PW',
        'HOST' : 'tcp:dbname.database.windows.net',
        'PORT': '1442',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
            }
    },
}

I've tried removing "tcp:" from host, I've tried "sql_server.pyodbc" as the ENGINE. I installed a few different other packages.

Whenever I run "python manage.py inspectdb > models.py" to import the models of the existing database I either get an empty models.py file or an error "django.db.utils.Error: ('01000'...". Feel a bit stuck and was wondering if anyone had some guidance.

You need to make some changes in your configuration. The USER should be in <user>@<servername> format. And you can keep the PORT blank.

The most useful and recommended way to connect the Django App with Azure SQL Database is by following the django-puodbc-azure README to install python packages pyodbc & django-pyodbc-azure and configure the settings.py file of Django as shown below:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'mydb',
        'USER': 'user@myserver',
        'PASSWORD': 'password',
        'HOST': 'myserver.database.windows.net',
        'PORT': '',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
        },
    },
}

Also, download the correct ODBC driver which is compatible to connect with Azure SQL Database.

Download from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM