我有一个问题,FastAPI与SQLModel耦合,我不明白为什么它不工作。我有以下模型:
class DeckBase(SQLModel):
name: str = Field(sa_column=Column(TEXT))
# region Foreign keys
owner_id: int = Field(foreign_key="player.id")
# endregion Foreign keys
class Deck(DeckBase, table=True):
id: int = Field(primary_key=True)
# region Relationship (access to the foreign key model)
owner: Player = Relationship(back_populates="decks")
cards: List["Card"] = Relationship(back_populates="decks", link_model=DeckCards) # ManyToMany
# endregion Relationship (access to the foreign key model)
字符串
下面是数据库表示:
的数据
我还定义了以下函数来根据SQLModel文档检索所有deck:
@router.get("/", response_model=List[DeckRead])
async def read_all(offset: int = 0,
limit: int = Query(default=100, le=100),
db: Session = Depends(DbContext().get_db)):
decks = db.execute(select(Deck).offset(offset).limit(limit)).all()
return decks
型
其中DeckRead
为:
class DeckRead(DeckBase):
id: int
型
但是当我调用路由时,我得到了这个错误:
[2024-01-02 18:37:19] [ERROR ] uvicorn.error: Exception in ASGI application
Traceback (most recent call last):
... (skipping the traceback)
fastapi.exceptions.ResponseValidationError: 3 validation errors:
{'type': 'missing', 'loc': ('response', 0, 'name'), 'msg': 'Field required', 'input': (Deck(id=1, name='Fire deck', owner_id=1),), 'url': 'https://errors.pydantic.dev/2.5/v/missing'}
{'type': 'missing', 'loc': ('response', 0, 'owner_id'), 'msg': 'Field required', 'input': (Deck(id=1, name='Fire deck', owner_id=1),), 'url': 'https://errors.pydantic.dev/2.5/v/missing'}
{'type': 'missing', 'loc': ('response', 0, 'id'), 'msg': 'Field required', 'input': (Deck(id=1, name='Fire deck', owner_id=1),), 'url': 'https://errors.pydantic.dev/2.5/v/missing'}
型
为什么它不起作用?还有,让我烦恼的是,做下面的代码工作得很好:
@router.get("/", response_model=List[DeckRead])
async def read_all(offset: int = 0,
limit: int = Query(default=100, le=100),
db: Session = Depends(DbContext().get_db)):
decks = db.get(Deck, 1)
return [decks]
型
看起来all()
函数返回了fastapi无法理解的内容
谢谢你,谢谢
2条答案
按热度按时间guicsvcw1#
SQLModel使用一个特殊的
exec
函数,它 Package 了来自SQLAlchemy的底层execute
。字符串
应该可以
这样做的原因是SQLALchemy的
execute
将返回一个元组列表(因为您可以select
多个模型),除非您将.scalars()
添加到查询中。SQLModel有一个特殊的函数,用于只select
一个模型的特定情况。huus2vyu2#
问题似乎与响应模型和数据库返回的实际数据不匹配有关。
read_all
函数试图返回Deck示例列表,但response_model
被指定为List[DeckRead]
。由于DeckRead包含一个额外的字段(id
),FastAPI期望响应数据具有此字段,导致验证错误。试试这个:
字符串