Closed dantetemplar closed 7 months ago
Actually, I've struggled with json schema for beanie Link....
That's my solution for replacing _id
with id
in FastAPI, and dividing Input and Output shemas for Generic Link
__all__ = ["CustomDocument", "CustomLink"]
from typing import Type, Any, TypeVar, get_args
from beanie import Document, PydanticObjectId, Link
from beanie.odm.registry import DocsRegistry
from pydantic import Field, ConfigDict, GetCoreSchemaHandler
from pydantic_core import CoreSchema, core_schema
class CustomDocument(Document):
model_config = ConfigDict(json_schema_extra={})
id: PydanticObjectId | None = Field(default=None, description="MongoDB document ObjectID", serialization_alias="id")
class Settings:
keep_nulls = False
max_nesting_depth = 1
D = TypeVar("D", bound=Document)
class CustomLink(Link[D]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Type[Any], handler: GetCoreSchemaHandler) -> CoreSchema:
document_class = DocsRegistry.evaluate_fr(get_args(source_type)[0])
document_class: Type[Document]
serialization_schema = core_schema.plain_serializer_function_ser_schema(
lambda instance: cls.serialize(instance),
return_schema=core_schema.union_schema(
[
core_schema.typed_dict_schema(
{
"id": core_schema.typed_dict_field(core_schema.str_schema()),
"collection": core_schema.typed_dict_field(core_schema.str_schema()),
}
),
document_class.__pydantic_core_schema__,
],
),
)
schema = core_schema.json_or_python_schema(
python_schema=core_schema.with_info_plain_validator_function(cls.build_validation(handler, source_type)),
json_schema=core_schema.with_default_schema(core_schema.str_schema(), default="5eb7cf5a86d9755df3a6c593"),
serialization=serialization_schema,
)
return schema
This issue is stale because it has been open 30 days with no activity.
This issue was closed because it has been stalled for 14 days with no activity.
someday I will create PR...
Describe the bug The
beanie.odm.fields.Link.__get_pydantic_core_schema__
method has tworeturn
statements, while the second one is never executed.To Reproduce https://github.com/roman-right/beanie/blob/e2d95be0843375353d6ec79a230f63d4f874ee0e/beanie/odm/fields.py#L396-L419
Expected behavior No redundant return statement inside the method; Also this method should not use deprecated
pydantic_core.core_schema.general_plain_validator_function