I want to use "./manage.py shell" to run some Python commands with a specific tenant, but the code to do so is quite cumbersome because I first have to look up the tenant and then use with tenant_context(tenant)): and then write my code into this block.
I thought that there should be a command for that provided by django-tenants, but there isn't.
I've just looked at this myself and this will work, where tenant1 is your chosen tenant:
python3 manage.py tenant_command shell --schema=tenant1
I have written my own small management command for that, which needs to be adjusted to use your own tenant model:
# <module>/management/commands/tenant_shell.py
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django_tenants.utils import tenant_context
# TODO: Use your own tenant model
from core.models import Tenant
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("-t", "--tenant", nargs=1)
def handle(self, *args, **options):
if options["tenant"] is None:
print("ERROR: please supply a tenant with the -t or --tenant option")
return
tenant_name = options["tenant"][0]
# TODO: Use your own filter logic (I have a field "name" in my model)
tenants = Tenant.objects.filter(name=tenant_name)
if len(tenants) == 0:
print("ERROR: tenant", tenant_name, "does not exist")
return
print("Run Python shell with tenant", tenant_name)
with tenant_context(tenants[0]):
del options["tenant"]
del options["skip_checks"] # TODO I don't know why this extra parameter is passed here?
call_command("shell", *args, **options)
You can then run the tenant Python shell with
python ./manage.py tenant_shell -t "Tenant Name"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With