skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search