0

I created a Django application and connected it to SQL Server with a trusted connection. When I migrate, Django is creating a new schema name (trusted connection username) in the database and adding this on all tables as prefix. By my IT department convention, all tables should be created with the 'dbo' prefix.

The most interesting part is: When I access the database from SSMS (also with trusted connection), and create a new database, I do not have this issue, it creates as 'dbo.table_name'.

Does anybody knows how can I fix it? See below better example and some code.

Summary:
Django creating: 'my_username.table_name'
I need: 'dbo.table_name'

My django settings.py

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'dabase_name',
        'HOST': 'database_host',
        'USER': '',

    'OPTIONS': {
            'driver': "ODBC Driver 17 for SQL Server",
            'Trusted_Connection' : 'Yes',
        }
    }
}

One of my models (table) as example:

class Sap_module(models.Model):
    sap_module = models.CharField(max_length=2, unique=True)
    available = models.BooleanField(default=True)

    def __str__(self):
        return self.sap_module
Dale K
  • 25,246
  • 15
  • 42
  • 71
Thiago Araujo
  • 149
  • 2
  • 14
  • There's an old hack that might not work anymore, set your db_table = 'dbo].[Sap_module' and Django will wrap in brackets and construct the table name as `[dbo].[Sap_module]` http://kozelj.org/django-1-6-mssql-and-schemas/ – mgrollins Nov 22 '19 at 00:07
  • @mgrollins, this might solve for the tables created from the models but not for django admin tables as I will not be able to include the code you mentioned above. I read the link you sent but it is only fixing the models... Thanks for your support. – Thiago Araujo Nov 22 '19 at 02:45
  • OK, yah I haven't worked through this issue myself. Can you set up your Django instance as a dual-DB with the admin in a SQLite DB on your server, and your model in the SQL Server DB? Then you could define the table names for the models in SQL Server. Django doesn't fully support SQL Server or schema's, which is what the `dbo` section of the table name represents. – mgrollins Nov 22 '19 at 19:12
  • Do you need the full admin/model functionality of Django? If your project is more data sciencey and you are just pulling data from a SAP model, perhaps Flask would be a better fit? I know Danny Greenfield uses Flask if it's not a DB backed (CRUD) app. – mgrollins Nov 22 '19 at 19:14
  • Actually it is working as it is, but I am not following the company standards... this is the only issue. Thanks a lot for your support. I still trying but at moment I will keep as it is. – Thiago Araujo Nov 23 '19 at 05:09
  • These 'hacks' are approaching 3 years old now, and do not seem to fully work for Django 3+. There's a failure during translation of 'dbName].[tableName' into T-SQL during migration. – André Foote Apr 06 '21 at 09:16

0 Answers0