I’m having difficulty getting the Database Router to migrate models to the correct database.
Reading and writing are working fine, but migrate is not. I have read documentation, search on other places on internet and still no luck.
This is my code for Database Router that is created in ./Baza2/db_router.py
class rout:
def db_for_read(self, model, **hints):
"""
Attempts to read auth and contenttypes models go to auth_db.
"""
if model._meta.app_label == "Baza2":
return "db2"
return None
def db_for_write(self, model, **hints):
"""
Attempts to read auth and contenttypes models go to auth_db.
"""
if model._meta.app_label == "Baza2":
return "db2"
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == "Baza2":
return db == "db2"
return None
This is for ./settings.py
DATABASE_ROUTERS = ["Baza2.db_router.rout"]
This is for models in ./Baza2/models.py
class City(models.Model):
city_name = models.CharField( max_length=30, blank=True, null=True)
def __str__(self):
return self.city_name
And this is in settings.py for databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'db2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db_second.sqlite3',
},
}
This is very basic code for this example but Im missing something. I
m beginner for programing. If I start debug process for migrate command and create breakpoint in ./Baza2/db_router.py at first line of code for migration
if app_label == "Baza2":
and then go slowly with Step Into line by line, when app_label is True to “Baza2” db stay ‘default’. And the result is in ‘default’ DB django create all tables that are always needed, and ‘db2’ DB stays empty. I try some other staff but will be to long to explain everything.