Skip to content

Commit

Permalink
add test_contained_by_subquery (broken)
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Jan 8, 2025
1 parent aff20ae commit 19502fc
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
8 changes: 7 additions & 1 deletion django_mongodb_backend/fields/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,13 @@ class ArrayContainedBy(ArrayRHSMixin, FieldGetDbPrepValueMixin, Lookup):
def as_mql(self, compiler, connection):
lhs_mql = process_lhs(self, compiler, connection)
value = process_rhs(self, compiler, connection)
return {"$and": [{"$ne": [lhs_mql, None]}, {"$setIsSubset": [lhs_mql, value]}]}
return {
"$and": [
{"$ne": [lhs_mql, None]},
{"$ne": [value, None]},
{"$setIsSubset": [lhs_mql, value]},
]
}


@ArrayField.register_lookup
Expand Down
74 changes: 74 additions & 0 deletions tests/model_fields_/test_arrayfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,80 @@ def test_contains_subquery(self):
self.objs[1:3],
)

def test_contained_by_subquery(self):
IntegerArrayModel.objects.create(field=[2, 3])
inner_qs = IntegerArrayModel.objects.values_list("field", flat=True)
self.assertSequenceEqual(
NullableIntegerArrayModel.objects.filter(field__contained_by=inner_qs[:1]),
self.objs[1:3],
)
IntegerArrayModel.objects.create(field=[2])
inner_qs = IntegerArrayModel.objects.filter(field__contained_by=OuterRef("field"))
# fails with "both operands of $setIsSubset must be arrays. Second
# argument is of type: null"
self.assertSequenceEqual(
NullableIntegerArrayModel.objects.filter(Exists(inner_qs)),
self.objs[1:3],
)

# [
# {
# "$lookup": {
# "as": "__subquery0",
# "from": "model_fields__integerarraymodel",
# "let": {"parent__field__0": "$field"},
# "pipeline": [
# {
# "$match": {
# "$expr": {
# "$and": [
# {"$ne": ["$field", None]},
# {"$ne": ["$$parent__field__0", None]},
# {"$setIsSubset": ["$field", "$$parent__field__0"]},
# ]
# }
# }
# },
# {"$project": {"a": {"$literal": 1}}},
# {"$limit": 1},
# ],
# }
# },
# {
# "$set": {
# "__subquery0": {
# "$cond": {
# "if": {
# "$or": [
# {"$eq": [{"$type": "$__subquery0"}, "missing"]},
# {"$eq": [{"$size": "$__subquery0"}, 0]},
# ]
# },
# "then": {},
# "else": {"$arrayElemAt": ["$__subquery0", 0]},
# }
# }
# }
# },
# {
# "$match": {
# "$expr": {
# "$eq": [
# {
# "$not": {
# "$or": [
# {"$eq": [{"$type": "$__subquery0.a"}, "missing"]},
# {"$eq": ["$__subquery0.a", None]},
# ]
# }
# },
# True,
# ]
# }
# }
# },
# ]

def test_contains_including_expression(self):
self.assertSequenceEqual(
NullableIntegerArrayModel.objects.filter(
Expand Down

0 comments on commit 19502fc

Please sign in to comment.