Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add Possibility of Leveraging Enum in find query #868

Merged
merged 1 commit into from
Feb 26, 2024
Merged
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
6 changes: 5 additions & 1 deletion beanie/odm/utils/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pathlib
import re
import uuid
from enum import Enum
from typing import (
Any,
Callable,
Expand Down Expand Up @@ -131,7 +132,10 @@ def encode(self, obj: Any) -> Any:
items = self._iter_model_items(obj)
return {key: self.encode(value) for key, value in items}
if isinstance(obj, Mapping):
return {str(key): self.encode(value) for key, value in obj.items()}
return {
key if isinstance(key, Enum) else str(key): self.encode(value)
for key, value in obj.items()
}
if isinstance(obj, Iterable):
return [self.encode(value) for value in obj]

Expand Down
17 changes: 17 additions & 0 deletions tests/odm/query/test_find.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
from enum import Enum

import pytest
from pydantic import BaseModel
Expand Down Expand Up @@ -399,3 +400,19 @@ def test_find_clone():
("string", SortDirection.ASCENDING),
]
assert new_q.limit_number == 10


async def test_find_many_with_enum_in_query(preset_documents):
class TestEnum(str, Enum):
INTEGER = Sample.integer
SAMPLE_NESTED_OPTIONAL = Sample.nested.optional
CONST = "const"
CONST_VALUE = "TEST"

filter_query = {
TestEnum.INTEGER: {"$gt": 1},
TestEnum.SAMPLE_NESTED_OPTIONAL: {"$type": "null"},
TestEnum.CONST: TestEnum.CONST_VALUE,
}
result = await Sample.find_many(filter_query).to_list()
assert len(result) == 2
Loading