Skip to content

Commit

Permalink
feat(core): add meta intersection filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Yelinz committed Aug 11, 2023
1 parent 935e7a9 commit 68d86db
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
11 changes: 11 additions & 0 deletions caluma/caluma_core/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.contrib.postgres.fields.hstore import KeyTransform
from django.contrib.postgres.search import SearchVector
from django.db import models
from django.db.models import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import OrderBy
from django.db.models.fields.json import KeyTextTransform
Expand Down Expand Up @@ -378,6 +379,7 @@ class JSONLookupMode(Enum):
CONTAINS = "contains"
ICONTAINS = "icontains"
IN = "in"
INTERSECTS = "intersects"
GTE = "gte"
GT = "gt"
LTE = "lte"
Expand Down Expand Up @@ -425,10 +427,19 @@ def filter(self, qs, value):
),
)
lookup = {f"field_val__{lookup_expr}": expr["value"]}
elif lookup_expr == JSONLookupMode.INTERSECTS:
lookup = {}
exprs = [
Q(**{f"{self.field_name}__{expr['key']}__contains": val})
for val in expr["value"]
]
# connect all expressions with OR
qs = qs.filter(reduce(lambda a, b: a | b, exprs))
else:
lookup = {
f"{self.field_name}__{expr['key']}__{lookup_expr}": expr["value"]
}

qs = qs.filter(**lookup)
return qs

Expand Down
2 changes: 2 additions & 0 deletions caluma/caluma_core/tests/test_meta_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
("CONTAINS", "bar", ["contains", "starts", "exact"]),
("ICONTAINS", "bar", ["icontains", "contains", "starts", "exact"]),
("IN", [1, 2], ["in"]),
("INTERSECTS", [1, 2], ["in", "intersects"]),
(None, True, ["bool"]),
(None, 123, ["int"]),
(None, 123.456, ["float"]),
Expand All @@ -30,6 +31,7 @@ def test_meta_value_filter(
"bool": document_factory(meta={"foo": True}),
"int": document_factory(meta={"foo": 123}),
"float": document_factory(meta={"foo": 123.456}),
"intersects": document_factory(meta={"foo": [2, 3]}),
}

query = """
Expand Down
1 change: 1 addition & 0 deletions caluma/tests/__snapshots__/test_schema.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -1671,6 +1671,7 @@
CONTAINS
ICONTAINS
IN
INTERSECTS
GTE
GT
LTE
Expand Down

0 comments on commit 68d86db

Please sign in to comment.