Skip to content

Commit 1c6e93d

Browse files
committed
Add direct query lookup tests.
1 parent e8ecf50 commit 1c6e93d

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

tests/lookup_/tests.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,90 @@ def test_eq_and_in(self):
7373
"lookup__book",
7474
[{"$match": {"$and": [{"isbn": {"$in": ("12345", "56789")}}, {"title": "Moby Dick"}]}}],
7575
)
76+
77+
def test_gt(self):
78+
with self.assertNumQueries(1) as ctx:
79+
list(Number.objects.filter(num__gt=2))
80+
self.assertAggregateQuery(
81+
ctx.captured_queries[0]["sql"],
82+
"lookup__number",
83+
[
84+
{"$match": {"num": {"$gt": 2}}},
85+
{"$addFields": {"num": "$num"}},
86+
{"$sort": SON([("num", 1)])},
87+
],
88+
)
89+
90+
def test_gte(self):
91+
with self.assertNumQueries(1) as ctx:
92+
list(Number.objects.filter(num__gte=2))
93+
self.assertAggregateQuery(
94+
ctx.captured_queries[0]["sql"],
95+
"lookup__number",
96+
[
97+
{"$match": {"num": {"$gte": 2}}},
98+
{"$addFields": {"num": "$num"}},
99+
{"$sort": SON([("num", 1)])},
100+
],
101+
)
102+
103+
def test_subquery_filter_constant(self):
104+
with self.assertNumQueries(1) as ctx:
105+
list(Number.objects.filter(num__in=Number.objects.filter(num__gt=2).values("num")))
106+
self.assertAggregateQuery(
107+
ctx.captured_queries[0]["sql"],
108+
"lookup__number",
109+
[
110+
{
111+
"$lookup": {
112+
"as": "__subquery0",
113+
"from": "lookup__number",
114+
"let": {},
115+
"pipeline": [
116+
{"$match": {"num": {"$gt": 2}}},
117+
{
118+
"$facet": {
119+
"group": [
120+
{"$group": {"_id": None, "tmp_name": {"$addToSet": "$num"}}}
121+
]
122+
}
123+
},
124+
{
125+
"$project": {
126+
"num": {
127+
"$ifNull": [
128+
{
129+
"$getField": {
130+
"input": {"$arrayElemAt": ["$group", 0]},
131+
"field": "tmp_name",
132+
}
133+
},
134+
[],
135+
]
136+
}
137+
}
138+
},
139+
],
140+
}
141+
},
142+
{
143+
"$set": {
144+
"__subquery0": {
145+
"$cond": {
146+
"if": {
147+
"$or": [
148+
{"$eq": [{"$type": "$__subquery0"}, "missing"]},
149+
{"$eq": [{"$size": "$__subquery0"}, 0]},
150+
]
151+
},
152+
"then": {},
153+
"else": {"$arrayElemAt": ["$__subquery0", 0]},
154+
}
155+
}
156+
}
157+
},
158+
{"$match": {"$expr": {"$in": ["$num", "$__subquery0.num"]}}},
159+
{"$addFields": {"num": "$num"}},
160+
{"$sort": SON([("num", 1)])},
161+
],
162+
)

0 commit comments

Comments
 (0)