diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 045f7d194f..888d62793f 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -203,6 +203,13 @@ class In(BuiltinLookup): lookup_name = 'in' def process_rhs(self, compiler, connection): + db_rhs = getattr(self.rhs, '_db', None) + if db_rhs is not None and db_rhs != connection.alias: + raise ValueError( + "Subqueries aren't allowed across different databases. Force " + "the inner query to be evaluated using `list(inner_query)`." + ) + if self.rhs_is_direct_value(): try: rhs = set(self.rhs) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index 557d0895e7..aba6588ac8 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -498,6 +498,14 @@ class LookupTests(TestCase): ] ) + def test_in_different_database(self): + with self.assertRaisesMessage( + ValueError, + "Subqueries aren't allowed across different databases. Force the " + "inner query to be evaluated using `list(inner_query)`." + ): + list(Article.objects.filter(id__in=Article.objects.using('other').all())) + def test_error_messages(self): # Programming errors are pointed out with nice error messages with self.assertRaisesMessage(