diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 40ada52e29..21d357e32b 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -126,10 +126,10 @@ class RenamePermission(migrations.RunPython): from django.contrib.auth.models import Permission db = schema_editor.connection.alias - ctypes = ContentType.objects.filter( + ctypes = ContentType.objects.using(db).filter( app_label=self.app_label, model__icontains=old_model.lower() ) - for permission in Permission.objects.filter( + for permission in Permission.objects.using(db).filter( content_type_id__in=ctypes.values("id") ): prefix = permission.codename.split("_")[0] diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 7e8d01cbce..46fe310db2 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -1546,6 +1546,7 @@ class PermissionRenameOperationsTests(TransactionTestCase): "django.contrib.auth", "auth_tests", ] + databases = {"default", "other"} def setUp(self): app_config = apps.get_app_config("auth_tests") @@ -1605,6 +1606,26 @@ class PermissionRenameOperationsTests(TransactionTestCase): Permission.objects.filter(codename=f"{action}_newmodel").exists() ) + def test_permission_rename_other_db(self): + ct = ContentType.objects.using("default").create( + app_label="auth_tests", model="oldmodel" + ) + permission = Permission.objects.using("default").create( + codename="add_oldmodel", + name="Can add old model", + content_type=ct, + ) + # RenamePermission respects the database. + call_command("migrate", "auth_tests", verbosity=0, database="other") + permission.refresh_from_db() + self.assertEqual(permission.codename, "add_oldmodel") + self.assertFalse( + Permission.objects.using("other").filter(codename="add_oldmodel").exists() + ) + self.assertTrue( + Permission.objects.using("other").filter(codename="add_newmodel").exists() + ) + @mock.patch( "django.db.router.allow_migrate_model", return_value=False,