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 support for Indexed custom pydantic fields #754

Merged
merged 1 commit into from
Oct 24, 2023
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: 6 additions & 0 deletions beanie/odm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ def __new__(cls, *args, **kwargs):
def __get_pydantic_core_schema__(
cls, _source_type: Any, _handler: GetCoreSchemaHandler
) -> core_schema.CoreSchema:
custom_type = getattr(
typ, "__get_pydantic_core_schema__", None
)
if custom_type is not None:
return custom_type(_source_type, _handler)

return core_schema.no_info_after_validator_function(
lambda v: v,
simple_ser_schema(typ.__name__),
Expand Down
18 changes: 18 additions & 0 deletions tests/odm/documents/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from beanie.exceptions import CollectionWasNotInitialized
from beanie.odm.utils.projection import get_projection
from tests.odm.models import (
Color,
DocumentTestModel,
DocumentTestModelStringImport,
DocumentTestModelWithComplexIndex,
Expand Down Expand Up @@ -289,3 +290,20 @@ async def test_merge_indexes():

async def test_custom_init():
assert DocumentWithCustomInit.s == "TEST2"


async def test_index_on_custom_types(db):
class Sample1(Document):
name: Indexed(Color, unique=True)

class Settings:
name = "sample"

await db.drop_collection("sample")

await init_beanie(
database=db,
document_models=[Sample1],
)

await db.drop_collection("sample")