fastapi中需要的pydantic验证错误字段

发布于 2025-01-27 08:10:59 字数 2986 浏览 1 评论 0原文

在FastAPI应用中,我在尝试通过此端点获取数据时遇到了此错误:

@app.get(
    "/users/{telegram_id}",
    response_model=schemas.UserBase,
    tags=["user"],
    status_code=status.HTTP_200_OK,
)
def read_user(telegram_id: int, db: Session = Depends(get_db)):
    """Read user by telegram id."""
    db_user = crud.get_user(db, user_telegram_id=telegram_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )
    return db_user

路由器为:

def get_user(db: Session, user_telegram_id: int):
    """GEt user by telegram id."""
    return (
        db.query(models.User)
        .filter(models.User.telegram_id == user_telegram_id)
        .first()
    )

schemas as:

class UserArticlesSentView(BaseModel):
    """What fields will be in nested sent_articles list."""

    id: int
    # sent_articles: List[ArticleSentView] = []

    class Config:
        """Enable ORM mode."""

        orm_mode = True

class UserBase(BaseModel):
    """Base serializer for a user."""

    id: int
    telegram_id: int = Field(..., ge=0)
    username: str = Field(..., max_length=50)
    pet_name: str = Field(..., max_length=50)
    language_code: str = Field(..., max_length=3, min_length=2)
    sent_articles: List[UserArticlesSentView] = []

    class Config:
        """Enable ORM mode for all child methods."""

        orm_mode = True

用户库Pydantic模型包含send_articles字段,该字段必须包含带有“ id”:value的dicts列表。

验证错误是:

pydantic.error_wrappers.ValidationError: 2 validation errors for UserBase
response -> sent_articles -> 0 -> id
  field required (type=value_error.missing)
response -> sent_articles -> 1 -> id
  field required (type=value_error.missing)

此错误导致用户基架模式中的字段“ send_articles”。我不明白为什么。

我的型号

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    telegram_id = Column(Integer, unique=True, index=True)
    username = Column(String(50))
    pet_name = Column(String(50))
    language_code = Column(String(5))

    sent_articles = relationship("Log", back_populates="sent_to_user")


class Article(Base):
    __tablename__ = "articles"

    id = Column(Integer, primary_key=True, index=True)
    text = Column(String(1024))
    image_url = Column(String(500))
    language_code = Column(String(255), index=True)

    sent_to_user = relationship("Log", back_populates="sent_articles")


class Log(Base):
    __tablename__ = "sent_log"

    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    sent_to_user = relationship("User", back_populates="sent_articles")

    article_id = Column(Integer, ForeignKey("articles.id"), primary_key=True)
    sent_articles = relationship("Article", back_populates="sent_to_user")

    sent_time = (Column(DateTime(), server_default=text("NOW()")))

如何解决?

In FastAPI app I got this error while trying to fetch data by this endpoint:

@app.get(
    "/users/{telegram_id}",
    response_model=schemas.UserBase,
    tags=["user"],
    status_code=status.HTTP_200_OK,
)
def read_user(telegram_id: int, db: Session = Depends(get_db)):
    """Read user by telegram id."""
    db_user = crud.get_user(db, user_telegram_id=telegram_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )
    return db_user

Router is:

def get_user(db: Session, user_telegram_id: int):
    """GEt user by telegram id."""
    return (
        db.query(models.User)
        .filter(models.User.telegram_id == user_telegram_id)
        .first()
    )

Schemas are:

class UserArticlesSentView(BaseModel):
    """What fields will be in nested sent_articles list."""

    id: int
    # sent_articles: List[ArticleSentView] = []

    class Config:
        """Enable ORM mode."""

        orm_mode = True

class UserBase(BaseModel):
    """Base serializer for a user."""

    id: int
    telegram_id: int = Field(..., ge=0)
    username: str = Field(..., max_length=50)
    pet_name: str = Field(..., max_length=50)
    language_code: str = Field(..., max_length=3, min_length=2)
    sent_articles: List[UserArticlesSentView] = []

    class Config:
        """Enable ORM mode for all child methods."""

        orm_mode = True

UserBase pydantic model contains sent_articles field that must have a list of dicts with "id": value.

A validation error is:

pydantic.error_wrappers.ValidationError: 2 validation errors for UserBase
response -> sent_articles -> 0 -> id
  field required (type=value_error.missing)
response -> sent_articles -> 1 -> id
  field required (type=value_error.missing)

This error causes field "sent_articles" in UserBase schema. I do not understand why.

My models.py

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    telegram_id = Column(Integer, unique=True, index=True)
    username = Column(String(50))
    pet_name = Column(String(50))
    language_code = Column(String(5))

    sent_articles = relationship("Log", back_populates="sent_to_user")


class Article(Base):
    __tablename__ = "articles"

    id = Column(Integer, primary_key=True, index=True)
    text = Column(String(1024))
    image_url = Column(String(500))
    language_code = Column(String(255), index=True)

    sent_to_user = relationship("Log", back_populates="sent_articles")


class Log(Base):
    __tablename__ = "sent_log"

    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    sent_to_user = relationship("User", back_populates="sent_articles")

    article_id = Column(Integer, ForeignKey("articles.id"), primary_key=True)
    sent_articles = relationship("Article", back_populates="sent_to_user")

    sent_time = (Column(DateTime(), server_default=text("NOW()")))

How to solve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文