22from django .db import NotSupportedError
33from django .db .models import Index
44from django .db .models .expressions import Col
5+ from django .db .models .fields .related_lookups import In
56from django .db .models .lookups import BuiltinLookup
67from django .db .models .sql .query import Query
78from django .db .models .sql .where import AND , XOR , WhereNode
89
910from .query_utils import process_rhs
1011
12+ mongo_operators_idx = {
13+ "exact" : lambda a , b : {a : {"$eq" : b }},
14+ "gt" : lambda a , b : {a : {"$gt" : b }},
15+ "gte" : lambda a , b : {a : {"$gte" : b }},
16+ "lt" : lambda a , b : {a : {"$lt" : b }},
17+ "lte" : lambda a , b : {a : {"$lte" : b }},
18+ "in" : lambda a , b : {a : {"$in" : b }},
19+ }
20+
1121
1222def _get_condition_mql (self , model , schema_editor ):
1323 """Analogous to Index._get_condition_sql()."""
@@ -23,13 +33,21 @@ def builtin_lookup_idx(self, compiler, connection):
2333 lhs_mql = self .lhs .target .column
2434 value = process_rhs (self , compiler , connection )
2535 try :
26- return connection . mongo_operators_idx [self .lookup_name ](lhs_mql , value )
36+ return mongo_operators_idx [self .lookup_name ](lhs_mql , value )
2737 except KeyError :
2838 raise NotSupportedError (
29- f"MongoDB does not support the { self .lookup_name } lookup in indexes."
39+ f"MongoDB does not support the ' { self .lookup_name } ' lookup in indexes."
3040 ) from None
3141
3242
43+ def in_idx (self , compiler , connection ):
44+ if not connection .features .is_mongodb_6_0 :
45+ raise NotSupportedError (
46+ f"MongoDB does not support the { self .lookup_name } lookup in indexes."
47+ )
48+ return builtin_lookup_idx (self , compiler , connection )
49+
50+
3351def where_node_idx (self , compiler , connection ):
3452 if self .connector == AND :
3553 full_needed , empty_needed = len (self .children ), 1
@@ -38,13 +56,13 @@ def where_node_idx(self, compiler, connection):
3856 if self .connector == AND :
3957 operator = "$and"
4058 elif self .connector == XOR :
41- raise NotSupportedError ("Xor in indexes is not supported ." )
59+ raise NotSupportedError ("MongoDB does not support the 'Xor' lookup in indexes ." )
4260 else :
4361 if not connection .features .is_mongodb_6_0 :
44- raise NotSupportedError ("Or in indexes is not supported ." )
62+ raise NotSupportedError ("MongoDB does not support the 'Or' lookup in indexes ." )
4563 operator = "$or"
4664 if self .negated :
47- raise NotSupportedError ("Negated field in indexes is not supported ." )
65+ raise NotSupportedError ("MongoDB does not support negated field in indexes ." )
4866 children_mql = []
4967 for child in self .children :
5068 try :
@@ -77,5 +95,6 @@ def where_node_idx(self, compiler, connection):
7795
7896def register_indexes ():
7997 BuiltinLookup .as_mql_idx = builtin_lookup_idx
98+ In .as_mql_idx = in_idx
8099 Index ._get_condition_mql = _get_condition_mql
81100 WhereNode .as_mql_idx = where_node_idx
0 commit comments