1+ import operator
2+
13from django .db import NotSupportedError , connection
24from django .db .models import (
35 Index ,
46 Q ,
57)
68from django .test import (
79 TestCase ,
10+ skipIfDBFeature ,
11+ skipUnlessDBFeature ,
812)
913
1014from .models import Article
@@ -57,11 +61,23 @@ def test_raises_on_xor(self):
5761 )._get_condition_mql (Article , schema_editor = editor )
5862 self .assertEqual (context_manager .exception .args [0 ], "Xor in indexes is not supported." )
5963
64+ @skipIfDBFeature ("is_mongodb_6_0" )
65+ def test_raises_on_or (self ):
66+ with self .assertRaises (
67+ NotSupportedError
68+ ) as context_manager , connection .schema_editor () as editor :
69+ Index (
70+ name = "raises_on_negated" ,
71+ fields = ["headline" ],
72+ condition = Q (pk = True ) ^ Q (pk = False ),
73+ )._get_condition_mql (Article , schema_editor = editor )
74+ self .assertEqual (context_manager .exception .args [0 ], "Or in indexes is not supported." )
75+
76+ @skipUnlessDBFeature ("is_mongodb_6_0" )
6077 def test_composite_index (self ):
6178 with connection .schema_editor () as editor :
6279 index = Index (
6380 name = "composite_proposition" ,
64- # This is changed
6581 fields = ["headline" ],
6682 condition = Q (number__gte = 3 ) & (Q (text__gt = "test1" ) | Q (text__in = ["A" , "B" ])),
6783 )
@@ -86,3 +102,31 @@ def test_composite_index(self):
86102 ),
87103 )
88104 editor .remove_index (index = index , model = Article )
105+
106+ def test_composite_op_index (self ):
107+ for op in (
108+ [operator .or_ , operator .and_ ] if connection .features .is_mongodb_6_0 else [operator .and_ ]
109+ ):
110+ with self .subTest (operator = op ), connection .schema_editor () as editor :
111+ index = Index (
112+ name = "composite_proposition" ,
113+ fields = ["headline" ],
114+ condition = op (Q (number__gte = 3 ), Q (text__gt = "test1" )),
115+ )
116+ index ._get_condition_mql (Article , schema_editor = editor )
117+ mongo_operator = "$and" if op == operator .and_ else "$or"
118+ target = {mongo_operator : [{"number" : {"$gte" : 3 }}, {"text" : {"$gt" : "test1" }}]}
119+ self .assertEqual (
120+ target ,
121+ index ._get_condition_mql (Article , schema_editor = editor ),
122+ )
123+ editor .add_index (index = index , model = Article )
124+ with connection .cursor () as cursor :
125+ self .assertIn (
126+ index .name ,
127+ connection .introspection .get_constraints (
128+ cursor = cursor ,
129+ table_name = Article ._meta .db_table ,
130+ ),
131+ )
132+ editor .remove_index (index = index , model = Article )
0 commit comments