Home > front end >  Django Postgres database with multiple schema. How to add records to specific schema through shell
Django Postgres database with multiple schema. How to add records to specific schema through shell

Time:09-02

Iam currently working on django multi tenant using shared database with multiple schema approach. How can I add records to specific schema through shell.How can I get the specific schema database objects in views.py

In django we can get a model obect using Model.objects.all but in case of multiple schema how can i get the specific schema model object. Using SQL we can have SELECT * FROM [Schema].Model. How can we achieve this in django ORM?

CodePudding user response:

After lot of research I got an answer.

from django.db import connection
connection.schema_name = 'Your schema name'

Then filter the models it will only show the records in that schema. Suppose after assiging the schema connection.schema_name = 'Your schema name' and if we filter the User model User.objects.all() it will only shows the user objects in that schema.

If we set a schema name which is not present yet like connection.schema_name = 'Schema name which is not present' then we we filter the model it will always shows the public schema records.

CodePudding user response:

If you are using django-tenants you can use tenant_command to run a command on a specific schema (ie. tenant). You can find the tenant_command documentation here.

In your case, the command you're looking for is the following:

python3 manage.py tenant_command shell --schema [SCHEMA_NAME]

This will allow you to query and create objects that solely exists in the database schema of the provided tenant.

  • Related