The Django admin portal can clunky and slow in some places, but in this short article, I’m going to try to help make it more efficient for you, at a small price.


So, what’s wrong with it?

Well, the Django admin is a great tool for getting out a solid Django back-office user interface with minimal additional developer effort. Adding an admin interface for a Django model is literally a couple of lines of code away, and for a developer trying to balance making features work against making features accessible to non-technical people (like their clients), this is a great help.

However to make the Django admin easy to drop in comes at some costs, one of them being speed. Take the page counter.

Image for post

1 user in the DB (red box)

With just one user, the SQL queries look like this:

Image for post

Quite good, actually.

Notice the SELECT COUNT values in the request. For 1 user, that’s no problem. In fact, it’s okay even with 10k users:

Image for post

However, trying the same with 500k users causes the SQL times to begin to add up.

Image for post

Image for post

I’d demo with more users but I don’t want to bust my local DB for a screenshot

Anyone who deals with Django beyond small-scale may be familiar with this problem, especially when dealing with through models. For example, a social media backend might use through tables for recording subscriptions or comments (the big players tend to use Redis or some other cache implementation to serve those much more quickly, but for more permanent records a DB like Postgresql is the gold standard). You can imagine how quickly those tables would explode and make their admins unusable.

You can also opt to not use the admin, but what a waste that would be. So let’s see if we can fix it by removing the count queries.

#postgresql #sql #django #django-rest-framework

Speed up your Django Admin By Removing SQL Counts — Optimizing Django: Part 2
11.85 GEEK