﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
24026	migration RunPython operation ignores db router allow_migrate	dikamilo	nobody	"I wrote custom router for SaaS architecture to handle different databases and custom management command to apply migrations for all databases. I'm sure that this router and command works properly. 

All migrations works fine except migrations with {{{RunPython}}} command in operations - that migrations are executed ignoring {{{allow_migrate}}} policy in database router.

For example in one of my app i have several migrations generated by django (manage.py makemigrations). My router checks if given app models should be in given database and if it return False, django not create table, not change schema etc. All works just fine and model is not in database. But if I create empty migration and add RunPython operation that add initial data to database for given model, django execute this migration throwing out error {{{django.db.utils.OperationalError: no such table}}}.

I checked django code and for example in {{{AlterModelTable}}} operation {{{database_forwards}}} method uses {{{self.allowed_to_migrate}}}:

{{{
def database_forwards(self, app_label, schema_editor, from_state, to_state):
        old_apps = from_state.render()
        new_apps = to_state.render()
        old_model = old_apps.get_model(app_label, self.name)
        new_model = new_apps.get_model(app_label, self.name)
        if self.allowed_to_migrate(schema_editor.connection.alias, new_model):
            schema_editor.alter_db_table(
                new_model,
                old_model._meta.db_table,
                new_model._meta.db_table,
            )
}}}
To compare RunPython {{{database_forwards}}} method look like this (cut comments):

{{{
def database_forwards(self, app_label, schema_editor, from_state, to_state):
        self.code(from_state.render(), schema_editor)
}}}

I think it's a bug and {{{RunPython}}} command should use {{{self.allowed_to_migrate}}} too."	Bug	closed	Migrations	1.7	Normal	duplicate	migration		Unreviewed	0	0	0	0	0	0
