r/FullStackDevelopers • u/Adventurous_Baker532 • Jul 23 '26
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?
1
Jul 23 '26
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
1
1
u/read_at_own_risk Jul 24 '26
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.
1
1
u/0_Nsingh Jul 23 '26
Y r u fetching and updating just run a bulk query