Database Router I can`t apply migrations

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. Im 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.

Welcome @HighOrdinator !

Can you post the INSTALLED_APPS setting from your settings.py?

Do you have an apps.py file in your Baza2 directory? If so, what is in it?

What operating system are you using?

What versions of Django and Python are you using?

Side note: The standard Python & Django coding conventions define that class names should be capitalized. As a result, I would recommend you rename your router class as Rout instead of rout.

Thank you for welcome, replay and Side note.

It is new project in VS Code and Django. I created just to test this migration in DB Router for some larger project.
Here is INSTALLE_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Baza2',
]

From ./Baza2/apps.py

from django.apps import AppConfig

class Baza2Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Baza2'

Windows 10,
Django v = 5.1.6
Python v = 3.13.0

When running command python manage.py migrate, it applies migrations for the default database. In your case, this would lead to the Baza2 models not being created in this database: is this the case ? The table baza2_city must not exists in default database (but django_migrations table in this database would still mention that Baza2 migrations were applied - doing nothing - to this db)

If you want to also apply migrations to the db2 database (which would create your Baza2 models in it), you need to explicitly call python manage.py migrate --database db2. Does that work ?

Thank you for replay. Maybe I should mention at the beginning of the post that I wanted all the necessary tables in Django (for administrators, etc.) to be created in the default database, while all other tables that I need should be in a separate database.

  1. Yes. Only default tables are created in the default database. None of my table from ./Baza2/models.py are created anywhere.
  1. Yes, this is the case but I dont want this. (if I understand you)
  1. If I run python manage.py migrate --database db2 command all default tables and my table from ./Baza2/models.py are created in the ‘db2’ database and the default database is ignored. It stayed empty.

I want to do this automatically with Database Router part of code.

If you switch the allow_migrate method to

if app_label == "Baza2":
    return db == "db2"
elif db == "db2"
    return False
return None

that tells Django :
if model is from Baza2, then migrate if database is db2, otherwise don’t migrate (i.e Baza2 models are created in db2 but not in other databases)
else if database is db2, don’t migrate anything except what was migrated by the first if branch (i.e. non Baza2 models - django contribs, … - are not created in db2)
otherwise let other routers and Django decide what to do (i.e. in your case those other models - django contribs, … - will go into default database)

You still need to call both commands migrate AND migrate --database=db2

Thank you. It works.

I was thinking of logic in allow_migrate if models.py is coming from app Baza2 use db2 database other way use default one. And I just run migrate and it will be sorted out in if loop of allow_migrate. Is that even possible to create (code it)?

AFAIK and as it is documented in Multiple databases | Django documentation | Django, you cannot make migrations applied on all your database with a single call to migrate

Good to know. Thank you again.