Adding multiple database in Django project

Viewed 250

I tried maybe 100 samples but multiple database never worked in my projects. Please help me. I have tired more codes from various sites, but there is last codes in my project which I got from official website. All is the same with the Documentation but still not working.

Settings.py

DATABASE_ROUTERS = ['MyApp.routers.TenantRouter']
DATABASE_APPS_MAPPING = {'tenant': 'tenant'}

DATABASES = {
    'default': {
        'NAME': 'host_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': '******'
    },
   'tenant': {
        'NAME': 'tenant_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': '******'
    }
}

Routers.py

class TenantRouter:
    route_app_labels = {'tenant'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'tenant_data'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'tenant_data'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'tenant_data'
        return None

OneApp/models.py

class UserTbl(models.Model):
    username = models.CharField(max_length=50)

class Meta:
    app_label = 'tenant'
    db_table = u'UserTbl'

And using below line for migrate. But not migrating anything. It always says No migrations to apply.

python3 manage.py migrate --database=tenant
1 Answers

No migrations to apply means your project don't have any migrations files.

first you have to run python3 manage.py makemigrations OneApp it will create a migration file inside your OneApp/migrations directory then re-run python3 manage.py migrate OneApp --database=tenant command.

Related