@@ -66,3 +66,51 @@ def test_eq_and_in(self):
6666 "lookup__book" ,
6767 [{"$match" : {"$and" : [{"isbn" : {"$in" : ("12345" , "56789" )}}, {"title" : "Moby Dick" }]}}],
6868 )
69+
70+ def test_union_simple_conditions (self ):
71+ with self .assertNumQueries (1 ) as ctx :
72+ list (Book .objects .filter (title = "star wars" ).union (Book .objects .filter (isbn__in = "1234" )))
73+ self .assertAggregateQuery (
74+ ctx .captured_queries [0 ]["sql" ],
75+ "lookup__book" ,
76+ [
77+ {"$match" : {"title" : "star wars" }},
78+ {"$project" : {"_id" : 1 , "title" : 1 , "isbn" : 1 }},
79+ {
80+ "$unionWith" : {
81+ "coll" : "lookup__book" ,
82+ "pipeline" : [
83+ {"$match" : {"isbn" : {"$in" : ("1" , "2" , "3" , "4" )}}},
84+ {"$project" : {"_id" : 1 , "title" : 1 , "isbn" : 1 }},
85+ ],
86+ }
87+ },
88+ {"$group" : {"_id" : {"_id" : "$_id" , "title" : "$title" , "isbn" : "$isbn" }}},
89+ {"$addFields" : {"_id" : "$_id._id" , "title" : "$_id.title" , "isbn" : "$_id.isbn" }},
90+ ],
91+ )
92+
93+ def test_union_all_simple_conditions (self ):
94+ with self .assertNumQueries (1 ) as ctx :
95+ list (
96+ Book .objects .filter (title = "star wars" ).union (
97+ Book .objects .filter (isbn = "1234" ), all = True
98+ )
99+ )
100+ self .assertAggregateQuery (
101+ ctx .captured_queries [0 ]["sql" ],
102+ "lookup__book" ,
103+ [
104+ {"$match" : {"title" : "star wars" }},
105+ {"$project" : {"_id" : 1 , "title" : 1 , "isbn" : 1 }},
106+ {
107+ "$unionWith" : {
108+ "coll" : "lookup__book" ,
109+ "pipeline" : [
110+ {"$match" : {"isbn" : "1234" }},
111+ {"$project" : {"_id" : 1 , "title" : 1 , "isbn" : 1 }},
112+ ],
113+ }
114+ },
115+ ],
116+ )
0 commit comments