I begun to build an api with FastAPI in python and sqlalchemy : Here is a part of the models :
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")
After this, I create the schemas/models for pydantic (sry for long portion):
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
And the crud function I use with the api :
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()
The api route is :
@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
The result I've got is the next :
{
"id": 1,
"league_id": 10,
"radiant_score": 41,
"dire_score": 5,
"duration": 3541,
"is_valid": true,
"players": [
{}
]
}
I would like to populate "players" with the list of playerstats of the corresponding match (sorted by slot) as :
"players" : [
{
"slot": 0,
"hero_id": 14,
"num_kills": 54,
"isRadiant": true
},
{
"slot": 1,
"hero_id": 15,
"num_kills": 1,
"isRadiant": false
}
]
I think I need to chance one of the model/schema or the crud function but don't really know which one ? Also, maybe there is some pydantic schema that are useless or poorly built
PS : I followed the guideline of the FastAPI docs (which I recommend to read).
Thx for your help!