Skip to content

Instantly share code, notes, and snippets.

@gilsonbp
Created January 10, 2019 15:45
Show Gist options
  • Save gilsonbp/159ad48d73be1bc7f908b0f1d1e910ce to your computer and use it in GitHub Desktop.
Save gilsonbp/159ad48d73be1bc7f908b0f1d1e910ce to your computer and use it in GitHub Desktop.
To perform a query using Django ORM in a specific schema
from django.db import connection # Used for django tenants.
# I am assuming you are in the main public tenant.
connection.set_schema_to_public() # Switch to Public.
# Here is how you switch to a different tenant.
connection.set_schema("the-schema-name-of-your-tenant", True) # Switch to Tenant.
# You are now in the tenant you want, therefore any call you make will be made from that db schema.
# Therefore making this call is all you need after.
object = TableOne.objects.first()
@puroh
Copy link

puroh commented Jan 18, 2022

hello, i used this lines
from django_tenants.utils import get_tenant_model, tenant_context

def my_view(...):
for tenant in get_tenant_model().objects.exclude(schema_name="public"):
with tenant_context(tenant):
my_data = my_table_in_tenant.objects.all()
.....
....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment