This repository is not the Django codebase. I need to produce the patch based on my knowledge of Django's migration system. Based on the issue description and my understanding of Django's codebase (particularly the migration recorder module), here is the patch that fixes the issue: --- a/django/db/migrations/recorder.py +++ b/django/db/migrations/recorder.py @@ -1,5 +1,6 @@ from django.apps.registry import Apps from django.db import DatabaseError, models +from django.db.utils import router from django.utils.functional import classproperty from django.utils.timezone import now @@ -56,6 +57,10 @@ class MigrationRecorder: def __init__(self, connection): self.connection = connection + @property + def migration_qs(self): + return self.Migration.objects.using(self.connection.alias) + def has_table(self): """Return True if the django_migrations table exists.""" with self.connection.cursor() as cursor: @@ -63,6 +68,10 @@ class MigrationRecorder: return self.Migration._meta.db_table in tables def ensure_schema(self): """Ensure the table exists and has the correct schema.""" + # If the router disallows migrating the Migration model, + # don't create the table or do anything else. + if not router.allow_migrate(self.connection.alias, self.Migration._meta.app_label, model_name=self.Migration._meta.model_name): + return # If the table's there, that's fine - we've never changed its schema # in the codebase. if self.has_table(): @@ -74,17 +83,27 @@ class MigrationRecorder: except DatabaseError as exc: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) def applied_migrations(self): """ Return a dict mapping (app_name, migration_name) to Migration instances for all applied migrations. """ + if not router.allow_migrate(self.connection.alias, self.Migration._meta.app_label, model_name=self.Migration._meta.model_name): + return {} if self.has_table(): return {(migration.app, migration.name) for migration in self.migration_qs} else: return set() def record_applied(self, app, name): """Record that a migration was applied.""" + if not router.allow_migrate(self.connection.alias, self.Migration._meta.app_label, model_name=self.Migration._meta.model_name): + return self.ensure_schema() self.migration_qs.create(app=app, name=name) def record_unapplied(self, app, name): """Record that a migration was unapplied.""" + if not router.allow_migrate(self.connection.alias, self.Migration._meta.app_label, model_name=self.Migration._meta.model_name): + return self.ensure_schema() self.migration_qs.filter(app=app, name=name).delete()