Skip to main content

Command Palette

Search for a command to run...

1+N querys

Updated
1 min read
1+N querys
D

I am developer/code-reviewer/debugger/bug-fixer/architect/teacher/builder from dubai, uae

Widely know as N+plus one problem, it’s actually a misnomer. As @adamj.eu’s article neatly summarize with examples (and now my dyslexic mind actually understands it), it’s one query to get a list of N objects that you iterate over. And each iteration is a query as the initial query is lazy evaluated.

To avoid this in django, use:

  1. select_related (for one-to-one or one-to-many queries)

  2. prefetch_related (for many-to-many, many-to-one or generic-relations queries)

where it gets the related rows with the initial query, as the name indicates.

Always try and minimize the queries to a shared resource.

Happy hackin’

References: