SQLAlchemy - 1 db query instead of many, many, many

Viewed 38

I'm new to SQLAlchemy and am constantly fumbling with this, hopefully I can describe my problem properly.

I have a database with about 20 tables and many connections between them using foreign keys/relationships. A typical query I perform might look like this:

games = db.session.query(Game).outerjoin(Team, and_(Team.id==Game.team_home_id, Team.id==Game.team_away_id)).outerjoin(Odds, Odds.id==Game.odds_id).outerjoin(Chart).filter(Chart.ayanamsa_id==3, Chart.housesystem_id==1, Chart.name=="D1", Odds.home!=None, Odds.away!=None).all()

But I noticed that when I loop thrugh games, for example

class Match:
  def __init__ (self, data):
    self.id = data.id
    self.sport = data.sport.name
    self.home_name = data.team_home.mediumname
    self.away_name = data.team_away.mediumname
    self.home_odds = data.iseodds.home
    self.away_odds = data.iseodds.away
    self.home_scores = data.result_home
    self.away_scores = data.result_away

GamesData = []
for game in games:
  m = Match (game)
  GamesData.append (m)

it makes many queries to the database all the time - and when there are many thousands or hundreds of thousands of items, it takes a veeeeeery long time.

Instead of SQLAlchemy making thousands of queries to the database, I would like it to make one single BIG query and then loop through the results locally, which I think should be much much faster. But somehow I've gotten tangled up in it. What do I need to change?

Thanks for any help:)

0 Answers
Related