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

Fix bugs that are not compatible with pydantic2.x #191

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 20 additions & 6 deletions fastapi_crudrouter/core/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

from fastapi import Depends, HTTPException
from pydantic import create_model
from pydantic import __version__ as pydantic_version

from ._types import T, PAGINATION, PYDANTIC_SCHEMA

PYDANTIC_MAJOR_VERSION = int(pydantic_version.split(".", maxsplit=1)[0])

class AttrDict(dict): # type: ignore
def __init__(self, *args, **kwargs) -> None: # type: ignore
Expand All @@ -14,7 +16,10 @@ def __init__(self, *args, **kwargs) -> None: # type: ignore

def get_pk_type(schema: Type[PYDANTIC_SCHEMA], pk_field: str) -> Any:
try:
return schema.__fields__[pk_field].type_
if PYDANTIC_MAJOR_VERSION >= 2:
return schema.model_fields[pk_field].annotation
else:
return schema.__fields__[pk_field].type_
except KeyError:
return int

Expand All @@ -26,11 +31,20 @@ def schema_factory(
Is used to create a CreateSchema which does not contain pk
"""

fields = {
f.name: (f.type_, ...)
for f in schema_cls.__fields__.values()
if f.name != pk_field_name
}
if PYDANTIC_MAJOR_VERSION >= 2:
# pydantic 2.x
fields = {
fk: (fv.annotation, ...)
for fk, fv in schema_cls.model_fields.items()
if fk != pk_field_name
}
else:
# pydantic 1.x
fields = {
f.name: (f.type_, ...)
for f in schema_cls.__fields__.values()
if f.name != pk_field_name
}

name = schema_cls.__name__ + name
schema: Type[T] = create_model(__model_name=name, **fields) # type: ignore
Expand Down