astapi.exceptions.ResponseValidationError:外键中存在 N 个验证错误

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

我正在构建 FastAPI + sqlalchemy 应用程序,想要序列化不动产对象

solution
数据而不是 id

我有以下型号

from sqlalchemy import Column, DateTime, Integer, String, Enum, Boolean, BigInteger, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import JSONB
from app.database.session import Base
from enum import Enum as PyEnum
from typing import List

class Task(Base):
    __tablename__ = 'tasks'

    id = Column(String, unique=True, nullable=False, primary_key=True)
    creation_time = Column(DateTime, nullable=False)
    ...
    solution: Mapped[List["Solution"]] = relationship()


class Solution(Base):
    __tablename__ = 'solutions'

    id = Column(String, unique=True, nullable=False, primary_key=True)
    task_id: Mapped[str] = mapped_column(ForeignKey("tasks.id"))
    has_file = Column(Boolean, nullable=False, default=False)    
    ...

和模式

from pydantic import BaseModel
from sqlalchemy import Column, DateTime, Integer, String, Enum, Boolean, BigInteger, ForeignKey

class Task(BaseModel):
    id: str
    ...
    creation_time: datetime
    solution: Optional[Solution]

    class Config:
        orm_mode = True

class Solution(BaseModel):
    id: str
    task_id: int
    has_file: bool
    solution_status: str
    creation_time: datetime
    solution_data: Optional[Dict[str, Any]]
    solution_file_url: Optional[str]

    class Config:
        orm_mode = True
        arbitrary_types_allowed=True

我正在 fastapi 应用程序中返回对象

@app.get("/tasks/{task_id}", response_model=TaskSchema)
def get_tasks(task_id: str, db: Session = Depends(get_db)):
    task = db.query(Task).filter_by(id=task_id).one_or_none()
    if task:
        return task
    raise HTTPException(status_code=400, detail="Not found")

不带线

solution: Optional[Solution] 
代码返回有效的json

{
  "id": "1",
  "rq_id": "my_rq_id_1",
  "priority": 1,
  "status": "WAITING",
  "creation_time": "2024-12-16T09:06:22",
  "status_update_time": "2024-12-16T09:06:22",
  "has_files": true,
  "is_online": true
}

但是这一行我有一个错误:

raise ResponseValidationError(
51_fetcher_new-consumer-1   | fastapi.exceptions.ResponseValidationError: 7 validation errors:
51_fetcher_new-consumer-1   |   {'type': 'missing', 'loc': ('response', 'solution', 'id'), 'msg': 'Field required', 'input': [<app.models.solutions.Solution object at 0x7f6b3331ce50>]}
51_fetcher_new-consumer-1   |   {'type': 'missing', 'loc': ('response', 'solution', 'task_id'), 'msg': 'Field required', 'input': [<app.models.solutions.Solution object at 0x7f6b3331ce50>]}

如何返回

solution
字段的内容?

python sqlalchemy fastapi
1个回答
0
投票

¡你好!由于 Pydantic 模型中的问题激增,Pydantic 将

Task
定义为单个对象 (
solution
),但 SQLAlchemy 的定义
Optional[Solution]
是一个与很多关系相关的列表。
Puedes ajustar el esquema de Pydantic para reflejar esto, cambiando la definición a algo como:

solution

	
© www.soinside.com 2019 - 2024. All rights reserved.