Skip to content

Commit

Permalink
Have ThingyList.distinct() handle array fields like MongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
ramnes committed Oct 5, 2023
1 parent b00d466 commit 661427d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
14 changes: 13 additions & 1 deletion mongo_thingy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,19 @@ def __get_value(item):
item = item.view()
return item.get(key)

values = set(__get_value(item) for item in self)
values = []

def __append_value(value):
if value not in values:
values.append(value)

for item in self:
value = __get_value(item)
if isinstance(value, list):
for v in value:
__append_value(v)
else:
__append_value(value)
return list(values)

def view(self, name="defaults"):
Expand Down
17 changes: 15 additions & 2 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async def test_thingy_list_distinct_thingies():

distinct = foos.distinct("bar")
assert distinct.count(None) == 1
assert set(distinct) == {None, "baz", "qux"}
assert distinct == [None, "baz", "qux"]


async def test_thingy_list_distinct_dicts():
Expand All @@ -35,7 +35,20 @@ async def test_thingy_list_distinct_dicts():

distinct = foos.distinct("bar")
assert distinct.count(None) == 1
assert set(distinct) == {None, "baz", "qux"}
assert distinct == [None, "baz", "qux"]


# https://mongodb.com/docs/manual/reference/method/db.collection.distinct/#array-fields
async def test_thingy_list_distinct_array_fields():
foos = ThingyList()
foos.append(Thingy())
foos.append(Thingy())
foos.append(Thingy(bar=[1, 2]))
foos.append(Thingy(bar=[2, 3, [3]]))

distinct = foos.distinct("bar")
assert distinct.count(None) == 1
assert distinct == [None, 1, 2, 3, [3]]


async def test_thingy_list_view():
Expand Down

0 comments on commit 661427d

Please sign in to comment.