【发布时间】:2021-02-20 18:10:40
【问题描述】:
我开始在 python 和 sqlalchemy 中使用 FastAPI 构建一个 api: 这是模型的一部分:
class Game(Base):
__tablename__ = "games"
id = Column(Integer, primary_key=True, index=True)
league_id = Column(Integer)
radiant_score = Column(Integer)
dire_score = Column(Integer)
duration = Column(Integer)
is_valid = Column(Boolean, default=True)
playerstats = relationship("PlayerStat", back_populates="match")
class PlayerStat(Base):
__tablename__ = "playerstats"
match_id = Column(Integer, ForeignKey("games.id"), primary_key=True)
slot = Column(Integer, primary_key=True)
hero_id = Column(Integer, ForeignKey("heros.id"))
num_kills = Column(Integer, default=None)
isRadiant = Column(Boolean, default=None)
match = relationship("Game", back_populates="playerstats")
heros = relationship("Hero", back_populates="playerstats")
在此之后,我为 pydantic 创建了模式/模型(很长的部分):
class PlayerStatBase(BaseModel):
slot: int
hero_id: int
num_kills: int
isRadiant: bool
class PlayerStatCreate(PlayerStatBase):
pass
class PlayerStat(PlayerStatBase):
slot: int
hero_id: int
num_kills: int
isRadiant: bool
class Config:
orm_mode = True
class GameBase(BaseModel):
id: int
league_id: int
radiant_score: int
dire_score: int
duration: int
is_valid: bool
class GameCreate(GameBase):
pass
class Game(GameBase):
id: int
league_id: int
radiant_score: int
dire_score: int
duration: int
is_valid: bool
players: List[PlayerStat] = [{}]
class Config:
orm_mode = True
还有我在 api 中使用的 crud 函数:
def get_match(db: Session, match_id: int):
print(db.query(models.Game).filter(models.Game.id == match_id))
return db.query(models.Game).filter(models.Game.id == match_id).first()
api路由是:
@app.get("/matches/{match_id}", response_model=schemas.Game)
def read_game(match_id: int, db: Session = Depends(get_db)):
db_game = crud.get_match(db, match_id=match_id)
if db_game is None:
raise HTTPException(status_code=404, detail="Game not found")
return db_game
我得到的结果是下一个:
{
"id": 1,
"league_id": 10,
"radiant_score": 41,
"dire_score": 5,
"duration": 3541,
"is_valid": true,
"players": [
{}
]
}
我想用相应比赛的球员统计数据列表(按插槽排序)填充“球员”:
"players" : [
{
"slot": 0,
"hero_id": 14,
"num_kills": 54,
"isRadiant": true
},
{
"slot": 1,
"hero_id": 15,
"num_kills": 1,
"isRadiant": false
}
]
我想我需要尝试其中一个模型/模式或 crud 函数,但不知道是哪一个? 此外,也许有一些无用或构建不佳的 pydantic 模式
PS : 我遵循了 FastAPI 文档的指导方针(我推荐阅读)。
感谢您的帮助!
【问题讨论】:
标签: python-3.x database api sqlalchemy fastapi