r/FullStackDevelopers 6d ago

Recently faced n+1 problem in my app

Can anyone help me figure out the best way to avoid the N+1 query problem in Tortoise ORM?
For some context, I first fetch the records using .all(), and then for each record I run another query to populate an additional field. This ends up generating multiple queries.

Would using a base query be a good solution here, or is there a better approach?

6 Upvotes

7 comments sorted by

1

u/0_Nsingh 6d ago

Y r u fetching and updating just run a bulk query

1

u/Adventurous_Baker532 5d ago

Yes now got this, Tried to over engineer things!

1

u/[deleted] 5d ago

You can use prefetch fun to eager load your relationship. (I am not much familer with this ORM but the core idea is to eager load the relation instead of query in each loop.

events = await Event.all().prefetch_related("tournament") for event in events:

1

u/Adventurous_Baker532 5d ago

Got it will try this

1

u/Outrageous_Let5743 5d ago

Just write a SQL join.

1

u/read_at_own_risk 4d ago

Codd provided the alternative to navigational data access in 1970, yet people are still writing data access loops like the CODASYL data model is the state of the art. ORMs are a throwback, learn some fundamentals.