If you’re into web development or just software engineering in general, you might have crossed paths with Django-REST. Django-REST has become sort of a gold standard for developers who (with reasonable effort) want to build the quintessential web server of the 2010’s: Open Source, REST protocol, MVS design pattern, and on Python, no less.

While Django does quite a good job of hiding most of the dirty SQL under its veneer of Models and QuerySets, in some situations we want to be able to optimise expensive database queries, whether to reduce RTT or avoid wasting valuable server time. If you’re reading this, I’ll take it that you’re looking to optimise your Django queries already, so at the very least, let’s make sure that your optimisations are verified with measurements.

In this mini-series, I will cover various tips that you can use to help cut a lot of wasted server processing time out of your queries.

Before we start, just a couple of things about the setup.

I’m using the following for this series:

IDE — Pycharm

Python 3

Latest Django 1. Django 1 support ends in 2020, so it is recommended to use Django 3. Fortunately,** most of this series should apply just as well to Django 2 and 3.**

I will also assume you have an intermediate-level knowledge of Django so I can skip some bits of typical Django configuration.

With that out of the way, let’s get right into it.

In this episode: Get an SQL debugging middleware.

If you’re unfamiliar with middleware, basically your requests are filtered down a whole bunch of middleware. Some perform authentication, while others deal with CSRF tokens. For more information, Django has an article all about this.

Django also allows you to create your own middleware, which we’re going to make full use of here to print out the SQL queries that are executed with every request the server receives.

Github user vstoykov posted a middleware snippet which is really useful, and I have used it in my own development (with some modifications) to great effect as well. Upon receiving a request, this middleware basically:

#sqlite #python #sql #postgres #django

Django SQL Debugging with an SQL log middleware
1.50 GEEK