0

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?

rangarajan
  • 143
  • 5
  • 17
  • 1
    Yes, this adds quite a bit of complexity, you may wish to [refer to this thread](https://stackoverflow.com/questions/50819748/django-and-postgresql-schemas). – metatoaster Jun 25 '22 at 04:10

2 Answers2

2

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.

Nitish
  • 392
  • 2
  • 7
  • So, I just need to `'myapp"."custom_model'` as `db_table` in my `CustomModel` class and `user_profile` as `db_table` in my `UserProfile` model? will that do everything I mentioned for me? And will that create the schema `myapp` automatically? can you add more details to your solution? It will be more helpful. – rangarajan Jun 25 '22 at 05:50
  • No it won't create the schema for you. That you need to do manually. And yes for `CustomModel` you need to do that. And since you are creating `UserProfile` in public, you can just remove the `db_table` attribute and let Django do its thing. – Nitish Jun 25 '22 at 09:16
  • As you mentioned `SELECT * FROM "geo"."tablename"` will select the table from the schema `geo`, will that also create the table in the `geo` schema while running `migrate` command? – rangarajan Jun 25 '22 at 13:06
0

FOr Sql Server Use

class User(models.Model)
class Meta:
    db_table = '[schema].[tablename]'
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 16:56