Skip to content

Commit

Permalink
Handle views on result lists
Browse files Browse the repository at this point in the history
  • Loading branch information
ramnes committed Dec 14, 2022
1 parent 7ff4839 commit 4086534
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,19 @@ User({'_id': ObjectId(...), 'name': 'Mr. Foo', 'age': 1337})
### Apply views on cursors

```python
>>> for credentials in User.find().view("credentials"):
>>> cursor = User.find()
>>> for credentials in cursor.view("credentials"):
... print(credentials)
{'username': 'MrFoo', 'password': 't0ps3cr3t'}
{'username': 'MrsBar', 'password': '123456789'}
...
```

And if your cursor is already exhausted, you can still apply a view!

```python
>>> users = User.find().to_list(None)
>>> for credentials in users.view("credentials"):
... print(credentials)
{'username': 'MrFoo', 'password': 't0ps3cr3t'}
{'username': 'MrsBar', 'password': '123456789'}
Expand Down
8 changes: 8 additions & 0 deletions mongo_thingy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ def __get_value(item):
values = set(__get_value(item) for item in self)
return list(values)

def view(self, name="defaults"):
def __view(item):
if not isinstance(item, BaseThingy):
raise TypeError(f"Can't view type {type(item)}.")
return item.view(name)

return [__view(item) for item in self]


class BaseThingy(DatabaseThingy):
"""Represents a document in a collection"""
Expand Down
17 changes: 17 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ async def test_thingy_list_distinct_dicts():
assert set(distinct) == {None, "baz", "qux"}


async def test_thingy_list_view():
class Foo(Thingy):
pass

Foo.add_view("empty")
foos = ThingyList()
foos.append(Foo(bar="baz"))
foos.append(Foo(bar="qux"))

for foo in foos.view("empty"):
assert foo == {}

foos.append({})
with pytest.raises(TypeError):
foos.view("empty")


@pytest.mark.all_backends
async def test_base_thingy_database(TestThingy, database):
assert TestThingy.database == database
Expand Down

0 comments on commit 4086534

Please sign in to comment.