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.
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.
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!
Originally published on April 04, 2016