我无法在运行应用程序期间解决问题,也找不到答案。 当我运行代码时,出现下一个错误:
pydantic.errors.PydanticUndefinedAnnotation: name 'PostWithoutUserSchema' is not defined
我的架构位于一个目录中
schemas
。下一个代码来自schemas/user.py
:
if typing.TYPE_CHECKING:
from .post import PostWithoutUserSchema
class UserSchema(BaseModel):
id: int
username: str
model_config = ConfigDict(
from_attributes=True
)
class UserWithPostSchema(BaseModel):
id: int
username: str
posts: list['PostWithoutUserSchema'] = []
和
schemas/post.py
:
if typing.TYPE_CHECKING:
from .user import UserSchema
class PostSchema(BaseModel):
id: int
title: str
content: str
user: UserSchema
model_config = ConfigDict(
from_attributes=True
)
class PostWithoutUserSchema(BaseModel):
id: int
title: str
content: str
版本:
python = 3.11.4
fastapi = 0.109.2
pydantic = 2.6.1
使用
if typing.TYPE_CHECKING:
导入仅适用于 IDE 和类型检查器,但在运行时不起作用。
所以,你必须:
UserSchema
括起来post.py
和 user.py
导入您的应用程序if typing.TYPE_CHECKING:
主.py
from .user import UserWithPostSchema
u = UserWithPostSchema(id=1, username="")
用户.py
from pydantic import BaseModel, ConfigDict
from post import PostWithoutUserSchema
class UserSchema(BaseModel):
id: int
username: str
model_config = ConfigDict(from_attributes=True)
class UserWithPostSchema(BaseModel):
id: int
username: str
posts: list["PostWithoutUserSchema"] = []
post.py
import typing
from pydantic import BaseModel, ConfigDict
if typing.TYPE_CHECKING:
from .user import UserSchema
class PostSchema(BaseModel):
id: int
title: str
content: str
user: "UserSchema"
model_config = ConfigDict(from_attributes=True)
class PostWithoutUserSchema(BaseModel):
id: int
title: str
content: str