将架构导入 Pydantic 中的另一个架构时出错

问题描述 投票:0回答:1

我无法在运行应用程序期间解决问题,也找不到答案。 当我运行代码时,出现下一个错误:

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

python sqlalchemy fastapi pydantic
1个回答
0
投票

使用

if typing.TYPE_CHECKING:
导入仅适用于 IDE 和类型检查器,但在运行时不起作用。

所以,你必须:

  1. 用引号将
    UserSchema
    括起来
  2. post.py
    user.py
    导入您的应用程序
  3. 作为第 2 点的替代方案,您可以删除其中一个文件中的
    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
© www.soinside.com 2019 - 2024. All rights reserved.