Source code for ferrosoft.apps.ferrobase.management.commands.migratetenants
from django.core import management
from django.core.exceptions import ImproperlyConfigured
from django.core.management import BaseCommand
from ferrosoft.apps.ferrobase.models import Tenant
[docs]
class Command(BaseCommand):
"""Management command that runs Django migrations for every active tenant.
Iterates over active tenants in alphabetical order, activates each
tenant's database connection, and calls ``migrate``. Accepts optional
``app_label`` and ``migration_name`` arguments that are forwarded verbatim
to ``migrate``, allowing targeted migration or rollback for all tenants.
"""
[docs]
def add_arguments(self, parser):
parser.add_argument(
"app_label",
nargs="?",
type=str,
help="App label of an application to synchronize the state.",
)
parser.add_argument(
"migration_name",
nargs="?",
type=str,
help="Database state will be brought to the state after that migration. "
'Use the name "zero" to unapply all migrations.',
)
[docs]
def handle(self, *args, **options):
for tenant in Tenant.all_ordered():
try:
tenant.activate_connection()
self.stdout.write(
self.style.WARNING(
"Migrating tenant %s (database %s)..."
% (
tenant.name,
tenant.database_name,
)
)
)
management.call_command(
"migrate",
database=tenant.database_name,
**options,
)
except ImproperlyConfigured as e:
self.stdout.write(
self.style.ERROR("Cannot migrate tenant %s: %s" % (tenant.name, e))
)