How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Django · Python

Fix N+1 Query Performance Issue: django.db.backends: (0.002) SELECT ... FROM "orders_order" WHERE "orders_order"."customer_id" = %s; args=(1,) [repeated 200+ times] in Django

This performance issue occurs when Django executes a separate query for each related object in a loop, instead of fetching them all at once. Fix it by using select_related() for ForeignKey/OneToOne relationships or prefetch_related() for ManyToMany/reverse ForeignKey relationships in your queryset.

Reading the Stack Trace

WARNING: django.db.backends logged 203 queries in 1.2s for view 'customer_list' SELECT "customers_customer"."id", "customers_customer"."name" FROM "customers_customer" SELECT "orders_order".* FROM "orders_order" WHERE "orders_order"."customer_id" = 1 SELECT "orders_order".* FROM "orders_order" WHERE "orders_order"."customer_id" = 2 SELECT "orders_order".* FROM "orders_order" WHERE "orders_order"."customer_id" = 3 ... (200 more queries) Traceback (most recent call last): File "/app/customers/views.py", line 12, in customer_list customers = Customer.objects.all() File "/app/customers/templates/customers/list.html", line 5 {% for order in customer.orders.all %} python-nplusone: Potential N+1 query detected on Customer.orders

Here's what each line means:

Common Causes

1. Missing prefetch_related on reverse FK

The queryset fetches all customers but does not prefetch their orders, causing a query per customer when the template iterates orders.

# views.py
def customer_list(request):
    customers = Customer.objects.all()
    return render(request, 'customers/list.html', {'customers': customers})

# template: list.html
{% for customer in customers %}
  {% for order in customer.orders.all %}
    {{ order.total }}
  {% endfor %}
{% endfor %}

2. Missing select_related on ForeignKey

Accessing a ForeignKey field in a loop without select_related triggers a query per row.

# views.py
def order_list(request):
    orders = Order.objects.all()
    return render(request, 'orders/list.html', {'orders': orders})

# template: list.html
{% for order in orders %}
  {{ order.customer.name }}  <!-- Triggers a query per order -->
{% endfor %}

3. Serializer accessing related objects

A DRF serializer accesses related fields without the view optimizing the queryset.

class OrderSerializer(serializers.ModelSerializer):
    customer_name = serializers.CharField(source='customer.name')

    class Meta:
        model = Order
        fields = ['id', 'total', 'customer_name']

# views.py — no select_related
class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

The Fix

Use prefetch_related('orders') for reverse ForeignKey relationships (one customer has many orders) and select_related('customer') for forward ForeignKey relationships (each order has one customer). This reduces 200+ queries down to 2.

Before (broken)
# views.py
def customer_list(request):
    customers = Customer.objects.all()
    return render(request, 'customers/list.html', {'customers': customers})
After (fixed)
# views.py
def customer_list(request):
    customers = Customer.objects.prefetch_related('orders').all()
    return render(request, 'customers/list.html', {'customers': customers})

# For ForeignKey access (e.g., order.customer.name):
def order_list(request):
    orders = Order.objects.select_related('customer').all()
    return render(request, 'orders/list.html', {'orders': orders})

Testing the Fix

import pytest
from django.test import TestCase
from django.test.utils import override_settings


class TestNPlusOneQuery(TestCase):
    def setUp(self):
        from customers.models import Customer
        from orders.models import Order
        for i in range(10):
            customer = Customer.objects.create(name=f'Customer {i}')
            Order.objects.create(customer=customer, total=100)

    def test_customer_list_uses_prefetch(self):
        with self.assertNumQueries(2):  # 1 for customers, 1 for orders
            response = self.client.get('/customers/')
            assert response.status_code == 200
            # Force template evaluation
            response.content

    def test_order_list_uses_select_related(self):
        with self.assertNumQueries(1):  # Single JOIN query
            response = self.client.get('/orders/')
            assert response.status_code == 200
            response.content

    def test_customer_list_shows_all_customers(self):
        response = self.client.get('/customers/')
        assert response.status_code == 200
        self.assertContains(response, 'Customer 0')

Run your tests:

pytest

Pushing Through CI/CD

git checkout -b fix/n-plus-one-query-customers,git add customers/views.py orders/views.py,git commit -m "fix: add prefetch_related and select_related to eliminate N+1 queries",git push origin fix/n-plus-one-query-customers

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: test_db
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pip install nplusone
      - run: pytest --tb=short -q

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the full test suite locally with assertNumQueries checks.
  2. Open a pull request with the query optimization.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and monitor query counts in staging with django-debug-toolbar.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, adds assertNumQueries tests, and validates that the optimized queries return identical results to the unoptimized version before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Use select_related for ForeignKey and OneToOneField (it does a SQL JOIN). Use prefetch_related for ManyToManyField and reverse ForeignKey relations (it does a separate query with an IN clause).

Install django-nplusone or use django-debug-toolbar in development. You can also use assertNumQueries in tests to enforce query count limits.