3

I'm using django-pyodbc-azure (https://github.com/michiya/django-pyodbc-azure) and everything is working fine. However, when I migrate the models, a new schema called 'dbo' is created on the SQL Server database. I want to use an already existing 'sp' schema, is there any way to set the working schema?

Thanks in advance.

ikermdagirre
  • 53
  • 1
  • 5

3 Answers3

5

IIRC, you need to change the default schema for the user your are connecting as. If you're using a SQL Auth user called django_user:

ALTER USER django_user WITH DEFAULT_SCHEMA = [sp]

Good luck.

FlipperPA
  • 13,607
  • 4
  • 39
  • 71
  • Thanks for the answer. I hoped this could be set in Django database settings, but it seems it's not possible. – ikermdagirre Feb 15 '16 at 07:39
  • It isn't doable without some really ugly hacks! It's best to just create a new SQL Auth user with a default schema. – FlipperPA Feb 15 '16 at 11:16
  • This still works in Django 3. Just be aware that changing the schema for the user, followed by applying migrations will result in all your tables being doubles. Thanks! – Steven Oct 06 '20 at 13:07
3

Define the db_table under the Meta class of one model as follows:

db_table = "[your_schema].[your_table]"
DrunkZemin
  • 51
  • 3
  • Can anyone confirm that this answer works? (Before we choose Django and MS SQL for a big project - we have lots of existing tables in different SQL schemas) – Reversed Engineer Dec 11 '17 at 16:17
  • This worked! I've been looking for a workaround for a week, you're a project-saver. – jyn Jun 18 '18 at 16:18
  • Note that this only works with schemas in an existing database, `sqlflush` and migrations will still fail. – jyn Jul 26 '18 at 12:56
  • 2
    This doesn't cover django default tables and library generated tables so I don't think it will solve the problem for most people. I need a way to globally specify a schema for the whole project. – ItsGeorge Aug 08 '19 at 13:42
1

I've found that a number of answers don't seem to work any more. Instead, I use the instructions found here to set the schema when defining db_table such as it goes schema].[table. Don't open those square brackets; the important bit is the ].[ between schema and table name.

In your case, you'd need to set:

class Meta:
    managed = False
    db_table = 'sp].[tablename'
James Wright
  • 156
  • 1
  • 7