DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why Should Databases Go Natural?
  • SQL Interview Preparation Series: Mastering Questions and Answers Quickly
  • Keep Calm and Column Wise
  • Why SQL Isn’t the Right Fit for Graph Databases

Trending

  • Integrating Security as Code: A Necessity for DevSecOps
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Data Engineering
  3. Databases
  4. Finding and Fixing Django N+1 Problems

Finding and Fixing Django N+1 Problems

One of the Django Python framework's best features is the Object-relational mapper (ORM), but sometimes the results are less than ideal.

By 
Adam McKerlie user avatar
Adam McKerlie
·
Sep. 17, 20 · News
Likes (1)
Comment
Save
Tweet
Share
4.3K Views

Join the DZone community and get the full member experience.

Join For Free

The Django Python framework allows people to build websites extremely fast. One of its best features is the Object-relational mapper (ORM), which allows you to make queries to the database without having to write any SQL. Django will allow you to write your queries in Python and then it will try to turn those statements into efficient SQL. Most of the time the ORM creates the SQL flawlessly, but sometimes the results are less than ideal.

One common database problem is that ORMs can cause N+1 queries. These queries include a single, initial query (the +1), and each row in the results from that query spawns another query (the N). These often happen when you have a parent-child relationship. You select all of the parent objects you want and then when looping through them, another query is generated for each child. This problem can be hard to detect at first, as your website could be performing fine. But as the number of parent objects grows, the number of queries increases as well — to the point of overwhelming your database and taking down your application.

Recently, I was building a simple website that kept track of expenses and expense reports. I wanted to use Sentry’s new Performance tool to assess how the application was performing in the production. I quickly set it up using the instructions for Django and immediately saw results.

The first thing I noticed was that the median root transaction was taking 3.41 seconds. All this page did was display a list of reports and the sum of all of the expenses on a report. Django is fast and it definitely shouldn’t take 3.41 seconds.

# models.py
from django.db import models
class Reports(models.Model):
    name = models.CharField(max_length=255)
    submitted_date = models.DateTimeField(null=True, blank=False)

    @property
    def get_expense_total(self):
        for expense in self.expenses.all():
            return expense.amount

class Expenses(models.Model):
    report = models.ForeignKey(Reports, related_name=‘expenses’, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=10, decimal_places=2)

# views.py
from django.views.generic.list import ListView
from expense_reports.models import Reports

class ReportsList(ListView):
    model = Reports
    context_object_name = 'reports'

# report_list.html
{% for report in reports %}
    <div>
        <h2>{{ report.name }}</h2>
        {% for expense in report.expenses.all %}
                <small>{{ expense.name }}</small>
                <small>{{ expense.amount }}</small>
        {% endfor %}
        <small>{{ report.get_expense_total }}</small>
    </div>
{% endfor %}

Looking at the code I couldn’t see any immediate problems, so I decided to dig into the Event Detail page for a recent transaction.

The second thing I noticed was just how many queries the ORM had generated. It was at this point that I saw that I had a single query to fetch all of the reports and then another query for each report to fetch all of the expenses —an N+1 problem.

Django evaluates queries lazily by default. This means that Django won’t run the query until the Python code is evaluated. In this case, when the page initially loads, Reports.objects.all() is called. When I call {{ report.get_expense_total }} Django runs the second query to fetch all of the expenses. There are two ways to fix this, depending on how your models are set up: [select_related()] and [prefetch_related()].

select_related() works by following one-to-many relationships and adding them to the SQL query as a JOIN. prefetch_related() works similarly, but instead of doing a SQL join it does a separate query for each object and then joins them in Python. This allows you to prefetch many-to-many and many-to-one relationships.

We can update ReportsList to use prefetch_related(). This cuts the number of database queries in half since we’re now making one query to fetch all of the Reports, one query to fetch all of the expenses, and then n queries in report.get_expense_total.

class ReportsList(ListView):
    model = Reports
    context_object_name = ‘reports’
    queryset = Reports.objects.prefetch_related(‘expenses’)

To fix the n queries from report.get_expense_total we can use Django’s annotate to pull in that information before passing it to the template.

# views.py
class ReportsList(ListView):
    model = Reports
    context_object_name = ‘reports’
    queryset = Reports.objects.prefetch_related(‘expenses’).annotate(total_amount=Sum(‘expenses__amount’))

# report_list.html
{% for report in reports %}
    <div>
        <h2>{{ report.name }}</h2>
        {% for expense in report.expenses.all %}
                <small>{{ expense.name }}</small>
                <small>{{ expense.amount }}</small>
         {% endfor %}
        <small>{{ report.total_amount }}</small>
    </div>
{% endfor %}

Now the median transaction time is down to 290ms!

In the event the number of queries increases to the point where it could take your application down, try using prefetch_related or select_related. This way, Django will fetch all of the additional information without the extra queries. After doing this, I ended up saving 950 queries on my main page and decreasing the page load by 91%.

Database Django (web framework) Relational database sql

Published at DZone with permission of Adam McKerlie. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why Should Databases Go Natural?
  • SQL Interview Preparation Series: Mastering Questions and Answers Quickly
  • Keep Calm and Column Wise
  • Why SQL Isn’t the Right Fit for Graph Databases

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!