Skip to content

fix GenericReference iterable query (i.e. __in) #2886

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions mongoengine/queryset/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,15 @@ def query(_doc_cls=None, **kwargs):

singular_ops = [None, "ne", "gt", "gte", "lt", "lte", "not"]
singular_ops += STRING_OPERATORS
is_iterable = False
if op in singular_ops:
value = field.prepare_query_value(op, value)

if isinstance(field, CachedReferenceField) and value:
value = value["_id"]

elif op in ("in", "nin", "all", "near") and not isinstance(value, dict):
is_iterable = True
# Raise an error if the in/nin/all/near param is not iterable.
value = _prepare_query_for_iterable(field, op, value)

Expand All @@ -144,10 +146,24 @@ def query(_doc_cls=None, **kwargs):
# * If the value is a DBRef, the key should be "field_name._ref".
# * If the value is an ObjectId, the key should be "field_name._ref.$id".
if isinstance(field, GenericReferenceField):
if isinstance(value, DBRef):
if isinstance(value, DBRef) or (
is_iterable and all(isinstance(v, DBRef) for v in value)
):
parts[-1] += "._ref"
elif isinstance(value, ObjectId):
elif isinstance(value, ObjectId) or (
is_iterable and all(isinstance(v, ObjectId) for v in value)
):
parts[-1] += "._ref.$id"
elif (
is_iterable
and any(isinstance(v, DBRef) for v in value)
and any(isinstance(v, ObjectId) for v in value)
):
raise ValueError(
"The `in`, `nin`, `all`, or `near`-operators cannot "
"be applied to mixed queries of DBRef/ObjectId/%s"
% _doc_cls.__name__
)

# if op and op not in COMPARISON_OPERATORS:
if op:
Expand Down
28 changes: 28 additions & 0 deletions tests/queryset/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,34 @@ class Shop(Document):

Shop.drop_collection()

def test_transform_generic_reference_field(self):
class Object(Document):
field = GenericReferenceField()

Object.drop_collection()
objects = Object.objects.insert([Object() for _ in range(8)])
# singular queries
assert transform.query(Object, field=objects[0].pk) == {
"field._ref.$id": objects[0].pk
}
assert transform.query(Object, field=objects[1].to_dbref()) == {
"field._ref": objects[1].to_dbref()
}

# iterable queries
assert transform.query(Object, field__in=[objects[2].pk, objects[3].pk]) == {
"field._ref.$id": {"$in": [objects[2].pk, objects[3].pk]}
}
assert transform.query(
Object, field__in=[objects[4].to_dbref(), objects[5].to_dbref()]
) == {"field._ref": {"$in": [objects[4].to_dbref(), objects[5].to_dbref()]}}

# invalid query
with pytest.raises(match="cannot be applied to mixed queries"):
transform.query(Object, field__in=[objects[6].pk, objects[7].to_dbref()])

Object.drop_collection()


if __name__ == "__main__":
unittest.main()