Django Postgres database with multiple schema. How to add records to specific schema through shell

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

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.

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 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.

Back to Top