Search code examples
pythondjangopostgresqldjango-modelsdjango-orm

How to create tables in a different schema in django?


I'm using postgresql database in my django project.

I have multiple apps in my projects.

users/
    UserProfile model
myapp/
    CustomModel model

Now I need UserProfile table should be created in public schema And CustomModel table needs to be created in a separate schema called myapp

How to implement this and Do I need to change anything in the queries or migration command in future after implementing this?


Solution

  • Just use a meta information:

    class User(models.Model)
        class Meta:
            db_table = 'schema"."tablename'
    

    I've been using it from some time and found not problem so far.

    More info: This will replace table name in all your database queries with db_table. So any query will SELECT * FROM "tablename" will be converted to SELECT * FROM "geo"."tablename". Its just a neat trick, hopefully Django gives this option natively in future.