I am new to Django, your help would be greatly appreciated. please let me know what mistakes i am making. can someone give me an example with at least 2 apps and 2 Databases.
I have 3 apps cherry, apple and mango in my Django project. For every app there is "models_cherry.py, models_apple.py and models_mango.py". I have created 3 databases in MySQL workbench DB1, DB2 and DB3.
When i fires following queries on windows PowerShell for migrations, it should create tables in the databases. migrations should be done on databases.
- python manage.py makemigrations 2) python manage.py migrate
The above commands create tables for only one model for one database.
My Question is, i want to create tables for all the models for all respective databases. i.e. For classes in file models_cherry.py into database DB1, for classes in file models_apple.py into DB2 and for classes in models_mango.py into DB3?
Here is a code for settings.py and routers files:
#Settings.py
DATABASE_ROUTERS =['apple.Routers.core_router.core_router', #Path to router file
'mango.Routers.man_router.man_router']
DATABASE_APPS_MAPPING = {'core':'core',
'man':'man'}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'PORT': '3306',
'NAME': 'DB1',
'USER': 'root',
'PASSWORD': 'root',
'OPTIONS': {
'autocommit': True,
},
},
'core': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'PORT': '3306',
'NAME': ' DB2',
'USER': 'root',
'PASSWORD': 'root',
'OPTIONS': {
'autocommit': True,
},
},
'man': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'PORT': '3306',
'NAME': ' DB3',
'USER': 'root',
'PASSWORD': 'root',
'OPTIONS': {
'autocommit': True,
},
},
}
# man_router.py
class man_router:
route_app_labels = {'man'}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'man'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'man'
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 == 'man'
return None
# core_router.py
class core_router:
route_app_labels = {'core'}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'core'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'core'
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 == 'core'
return None