Django ORM Optimization — ELI5

Imagine you’re making sandwiches for 30 kids at a party. You could walk to the fridge, grab one slice of cheese, walk back, put it on bread, then walk to the fridge again for the next slice. That’s 30 trips to the fridge for 30 sandwiches.

Or you could grab all 30 slices at once. One trip. Same result. Way faster.

Django’s ORM — the part of Django that talks to your database — sometimes acts like the person making 30 trips. Every time your code asks for related data (like “get me each blog post’s author”), Django might make a separate trip to the database for every single item. This is called the N+1 problem, and it’s the number one reason Django apps feel sluggish.

The fix is telling Django up front: “Hey, I’m going to need this related data, so grab it all in one go.” Django has built-in tools for this — select_related and prefetch_related — that bundle those trips together.

Another common slowdown is asking for everything when you only need a little. If you only need people’s names, don’t fetch their entire profile, photo, biography, and shoe size. Django lets you pick just the columns you need with values() or only().

The tricky part is that Django makes slow code look exactly like fast code. The syntax is identical. You won’t notice the problem until your page takes 4 seconds to load and your database is crying.

The one thing to remember: Most Django performance problems come from too many database trips — bundle your queries and only ask for what you actually need.

pythondjangodatabaseperformance

See Also