Skip to content

Commit

Permalink
Merge pull request #2828 from bagerard/allow_list_as_value_for_gte_lt…
Browse files Browse the repository at this point in the history
…e_ne

allow_list_as_value_for_gte_lte_ne
  • Loading branch information
bagerard authored Aug 25, 2024
2 parents 5a8b051 + ea1c3ee commit 95f8ba1
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Changelog
Development
===========
- (Fill this out as you fix issues and develop your features).
- Allow gt/gte/lt/lte/ne operators to be used with a list as value on ListField #2813
- Switch tox to use pytest instead of legacy `python setup.py test` #2804

Changes in 0.28.2
Expand Down
8 changes: 4 additions & 4 deletions mongoengine/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,11 +951,11 @@ def prepare_query_value(self, op, value):
if self.field:
# If the value is iterable and it's not a string nor a
# BaseDocument, call prepare_query_value for each of its items.
is_iter = hasattr(value, "__iter__")
eligible_iter = is_iter and not isinstance(value, (str, BaseDocument))
if (
op in ("set", "unset", None)
and hasattr(value, "__iter__")
and not isinstance(value, str)
and not isinstance(value, BaseDocument)
op in ("set", "unset", "gt", "gte", "lt", "lte", "ne", None)
and eligible_iter
):
return [self.field.prepare_query_value(op, v) for v in value]

Expand Down
39 changes: 39 additions & 0 deletions tests/queryset/test_field_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,45 @@ class User(Base):
with pytest.raises(LookUpError):
Base.objects.exclude("made_up")

def test_gt_gte_lt_lte_ne_operator_with_list(self):
class Family(Document):
ages = ListField(field=FloatField())

Family.drop_collection()

Family(ages=[1.0, 2.0]).save()
Family(ages=[]).save()

qs = list(Family.objects(ages__gt=[1.0]))
assert len(qs) == 1
assert qs[0].ages == [1.0, 2.0]

qs = list(Family.objects(ages__gt=[1.0, 1.99]))
assert len(qs) == 1
assert qs[0].ages == [1.0, 2.0]

qs = list(Family.objects(ages__gt=[]))
assert len(qs) == 1
assert qs[0].ages == [1.0, 2.0]

qs = list(Family.objects(ages__gte=[1.0, 2.0]))
assert len(qs) == 1
assert qs[0].ages == [1.0, 2.0]

qs = list(Family.objects(ages__lt=[1.0]))
assert len(qs) == 1
assert qs[0].ages == []

qs = list(Family.objects(ages__lte=[5.0]))
assert len(qs) == 2

qs = list(Family.objects(ages__ne=[5.0]))
assert len(qs) == 2

qs = list(Family.objects(ages__ne=[]))
assert len(qs) == 1
assert qs[0].ages == [1.0, 2.0]


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

0 comments on commit 95f8ba1

Please sign in to comment.