<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1870732089876948&amp;ev=PageView&amp;noscript=1">

Fewer Database Transactions with Better Django Queries

Application Development made easy with Django

Django is a web framework that makes it easy to interface your web app code with a relational database backend. The library allows developers to write database queries in simple Python code, and then translates them into SQL syntax behind the scenes. This extra layer of abstraction makes database transactions easier for developers to comprehend, and saves time that might have been spent debugging long SQL query strings.

For example, let’s say you have a table in your database of forms and you want to select the forms that have been approved by your Quality Assurance team. The Django query on the left is cleaner and more readable than the verbose SQL syntax on the right.

Django Query versus SQL Syntax | Cloudbakers

There will be cases, however, where simplicity comes at a cost to your app’s performance. Let’s say each Form has a foreign key to a record in the Client table, and you want to display information about each form and its associated client. You can make a separate database call each time you want to get a client’s info (like in the example below on the left), but if you have 10,000 forms to loop over, then that’s 10,000 extra queries! By using Django’s select_related method (like in the sample below on the right), you can select each form and its associated client from the database in a single query.

Django Query with and without Prefetch | Cloudbakers

Fewer database transactions will not only save time during page loads, but may also reduce the cost of hosting your application altogether.

For more advice on Django, see my previous post on proactive error reporting!


New Call-to-action

Originally published on April 04, 2016

If you enjoyed this post, please consider sharing

Want more tech tips?
Subscribe to our IT Superhero Newsletter!