python 无法将响应从Sqlalchemy转换为Pydantic模型

4nkexdtk  于 10个月前  发布在  Python
关注(0)|答案(1)|浏览(77)

我试图返回一个从Pydantic的BaseModel继承的模式,但我得到了一个错误
型号:

class Project(Base):
    __tablename__ = 'projects'

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(60), nullable=False)
    description: Mapped[str] = mapped_column()
    created_at: Mapped[date] = mapped_column(default=date.today())

    profiles: Mapped['Profile'] = relationship(
        back_populates='projects',
        secondary='project_profiles'
    )
    problems: Mapped[list['Problem']] = relationship(
        back_populates='project'
    )

方案:

class SProjectDetail(BaseModel):
    id: int
    title: str
    description: str
    created_at: date
    profiles: Optional[list[SProfile]] = []
    problems: Optional[list[SProblem]] = []

    class Config:
        orm_mode = True

class SProblem(BaseModel):
    id: int
    title: str

class SProfile(BaseModel):
    id: int
    lastname: str
    firstname: str

DAO:

class ProjectDAO(BaseDAO):
    model = Project

    @classmethod
    async def find_by_id(cls, id):
        async with async_session_maker() as session:
            query = select(Project,
                           Problem, 
                           Profile      
            ).outerjoin(
                Problem, Project.id == Problem.project_id
            ).outerjoin(
                Profile
            ).where(
                Project.id == id
            )

           
            print(query)
            result = await session.execute(query)
            return result.scalars().all()

路由器:

@router.get('/{id}')
async def get_project_by_id(id: int = Path(..., ge=0)) -> list[SProjectDetail]:
    return await ProjectDAO.find_by_id(id)

错误:enter image description here
我尝试从路由器响应enter image description here中删除pydantic模式

bsxbgnwa

bsxbgnwa1#

您可以在此处阅读有关此错误的信息:https://docs.sqlalchemy.org/en/20/errors.html#error-bhk3

  • 此错误消息表示对象已与其Session解除关联,并被要求从数据库延迟加载数据。*

因此,您尝试将其作为Pydantic读取,而它是延迟加载的,并且您的Session已经在ProjectDao中关闭。您可以在find_by_id方法中将其读取为Pydantic模型,也可以使用SQLModel中的Depends(Session)。这工作相当不错。这里有一个很好的例子:https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/#the-with-block。

相关问题