Django makes it remarkably easy to get an application up and running. Its ORM, model system, middleware, authentication framework and built-in utilities provide an excellent foundation for building web applications.

However, as applications grow, some decisions that initially seem convenient can introduce performance bottlenecks, unnecessary complexity and difficult-to-trace behaviour.

Some of these mistakes are easy to overlook because the code works perfectly well in development. The problems only become apparent when datasets grow, multiple developers contribute to the same application, or the system starts handling more complex workloads.

Let's explore some common Django mistakes, why they happen, and what we can do differently.


1. Using len() on a QuerySet

The mistake

One of the easiest mistakes to make is treating a Django QuerySet like an ordinary Python list.

Consider:

orders = Order.objects.filter(status="completed")

if len(orders) > 0:
    print("Completed orders found")

This works, but it isn't necessarily the most efficient approach.

Why is it problematic?

Django QuerySets are lazy. Constructing a QuerySet does not immediately execute the database query.

However, calling len() forces the QuerySet to be evaluated. Django retrieves the matching records and populates the QuerySet's result cache before determining its length.

If all you need is to establish whether records exist, retrieving every matching record is unnecessary.

The better approach

Use .exists() when you only need to know whether at least one record exists.

orders = Order.objects.filter(status="completed")

if orders.exists():
    print("Completed orders found")

If you need the actual number of matching records, use .count().

total_orders = Order.objects.filter(
    status="completed"
).count()

Understanding the differences

  • len(queryset) evaluates the QuerySet and retrieves its results if they haven't already been fetched.
  • queryset.count() performs a database count when the result cache isn't already populated.
  • queryset.exists() checks whether at least one matching record exists.

There is an important nuance: if you have already evaluated a QuerySet and need to iterate over it, using len() can be perfectly reasonable because Django can reuse the cached results.

Similarly, calling .exists() and then immediately iterating over the same unevaluated QuerySet can result in two database queries.

The lesson: Understand what you actually need before choosing how to evaluate a QuerySet.


2. Overusing Django Signals

The mistake

Django signals are useful. They provide a mechanism for allowing different parts of an application to respond to events without explicitly calling each other.

The problem is that signals are sometimes used where ordinary, explicit application logic would be more appropriate.

Consider:

# signals.py

@receiver(signal=post_save, sender=Order)
def order_completed(
    sender,
    instance,
    created,
    **kwargs
):
    if instance.status == "completed":
        send_confirmation_email(order=instance)

Elsewhere in the application:

order.status = "completed"
order.save()

The developer saving the order might have no idea that an email is also being sent.

Why is it problematic?

The issue isn't the signal itself. It's the implicit execution path.

A seemingly simple operation can trigger additional behaviour elsewhere in the application.

This introduces several challenges:

  • Discoverability: You need to know where receivers are registered to understand the complete execution path.
  • Debugging: Side effects can occur without being obvious from the code that initiated the operation.
  • Testing: Tests may trigger behaviour they weren't explicitly designed to exercise.
  • Coupling: Model operations can indirectly become responsible for multiple application-level actions.

There are also technical considerations. For example, post_save fires after a model's save() method, but that doesn't necessarily mean the surrounding database transaction has committed.

When do signals make sense?

Signals are useful when genuinely independent components need to react to an event.

For example:

  • Maintaining audit information.
  • Updating secondary application data.
  • Responding to model lifecycle events.
  • Integrating loosely coupled application components.

However, if completing an order must update inventory, generate an invoice and send a notification, I would generally prefer explicit orchestration.

The alternative: Explicit application logic

def complete_order(*, order):
    order.status = "completed"

    order.save(
        update_fields=["status"]
    )

    update_inventory(order=order)
    generate_invoice(order=order)
    send_confirmation_email(order=order)

Now the execution path is visible.

Of course, production implementations also need to consider transaction boundaries, failure handling, idempotency and whether external operations should happen after a successful database commit.

The lesson: Signals aren't bad practice. Using them indiscriminately can make application behaviour difficult to understand.

Explicit is better than implicit.


3. Ignoring N+1 Query Problems

The mistake

Consider a list of orders where each order has a related customer.

orders = Order.objects.all()

for order in orders:
    print(order.customer.name)

This looks perfectly reasonable.

However, depending on the relationship and how the QuerySet is loaded, Django may execute an additional database query for every order.

If you retrieve 100 orders, you could end up executing 101 queries.

This is commonly known as the N+1 query problem.

Why is it problematic?

Database queries have overhead.

Even relatively inexpensive queries become problematic when repeated unnecessarily, particularly when an application is dealing with thousands of records or concurrent requests.

The better approach

Django provides two particularly useful tools.

select_related()

Use this for single-valued relationships such as ForeignKey and OneToOneField.

orders = Order.objects.select_related(
    "customer"
)

for order in orders:
    print(order.customer.name)

Django uses SQL joins to retrieve the related customer data alongside the order.

prefetch_related()

Use this for multi-valued relationships such as ManyToManyField and reverse ForeignKey relationships.

orders = Order.objects.prefetch_related(
    "items"
)

for order in orders:
    for item in order.items.all():
        print(item.name)

Django retrieves the related records separately and joins them in Python.

When should you use each?

  • select_related() – ForeignKey and OneToOneField.
  • prefetch_related() – ManyToManyField and reverse relationships.

The lesson: Don't assume that accessing a related object is free. Understand how Django retrieves related data.


4. Putting Too Much Business Logic in Views

The mistake

Django views are responsible for handling requests and returning responses.

However, it's easy for them to become the home of every operation associated with a particular endpoint.

def create_order_view(*, request):
    if request.method == "POST":
        # Validate request data
        # Calculate pricing
        # Check inventory
        # Create order
        # Update stock
        # Send notification
        # Generate invoice
        # Return response
        ...

Before long, the view becomes difficult to understand, test and maintain.

Why is it problematic?

Business logic becomes tightly coupled to the HTTP request-response lifecycle.

This makes it harder to reuse the same functionality from:

  • Celery tasks.
  • Management commands.
  • Scheduled jobs.
  • Other application services.
  • Different API endpoints.

The better approach

Separate request handling from business operations.

For example:

# services.py

def create_order(*, customer, products):
    order = Order.objects.create(
        customer=customer
    )

    for product in products:
        OrderItem.objects.create(
            order=order,
            product=product
        )

    return order

Your view becomes much simpler:

def create_order_view(*, request):
    order = create_order(
        customer=request.user.customer,
        products=get_requested_products(
            request=request
        )
    )

    return JsonResponse(
        data={"order_id": order.id}
    )

This is a simple service-layer example. A production implementation would also need validation, atomic transactions and inventory concurrency protection.

The lesson: Views should coordinate HTTP interactions, not become the home of your entire business domain.


5. Performing Filtering in Python Instead of the Database

The mistake

Consider:

orders = Order.objects.all()

completed_orders = [
    order
    for order in orders
    if order.status == "completed"
]

This retrieves all orders and then filters them in Python.

Why is it problematic?

Imagine a table containing one million records, but you only need the completed orders from the last seven days.

Retrieving the entire table just to filter a small subset is wasteful.

You are transferring unnecessary data from the database, consuming memory and doing work that the database is designed to perform.

The better approach

Let the database do the filtering.

from datetime import timedelta

from django.utils import timezone

start_date = timezone.now() - timedelta(days=7)

completed_orders = Order.objects.filter(
    status="completed",
    date_created__gte=start_date
)

You can also chain filters and exclude conditions:

orders = Order.objects.filter(
    status="completed"
).exclude(
    total__lte=0
)

The resulting QuerySet remains lazy until evaluated.

The lesson: Filter, exclude, annotate and aggregate at database level whenever practical.


6. Misusing Database Transactions

The mistake

Transactions are essential when multiple database operations must succeed or fail together.

However, developers sometimes overlook transaction boundaries or keep transactions open longer than necessary.

Consider:

with transaction.atomic():
    order = Order.objects.create(
        customer=customer
    )

    response = requests.post(
        url="https://external-api.example.com/orders",
        json={"order_id": order.id},
        timeout=10
    )

    order.status = "submitted"

    order.save(
        update_fields=["status"]
    )

Why is it problematic?

The external HTTP request is taking place while the database transaction remains open.

If the external service takes several seconds to respond, the transaction remains open for that entire period.

This can result in:

  • Database locks being held longer.
  • Increased contention.
  • Reduced throughput.
  • More complicated failure scenarios.

Another problem is assuming that rolling back a database transaction will undo an external API request. It won't.

The better approach

Keep database transactions focused on database operations.

Django also provides transaction.on_commit() for scheduling callbacks after a successful transaction commit.

with transaction.atomic():
    order = Order.objects.create(
        customer=customer
    )

    transaction.on_commit(
        callback=lambda: submit_order(
            order_id=order.id
        )
    )

The callback runs only after the surrounding transaction successfully commits.

For more reliable integration with external services, particularly where delivery must survive application crashes, consider an outbox pattern or a durable background task.

The lesson: Database transactions protect database consistency. They don't automatically provide distributed transaction guarantees.


7. Ignoring Database Indexes

The mistake

Developers sometimes assume that adding indexes to every frequently queried field is the answer to slow database queries.

Others don't consider indexing at all.

Both approaches can be problematic.

Why is it important?

Indexes help the database locate records without scanning an entire table.

However, indexes also have costs:

  • Additional storage.
  • Increased write overhead.
  • More maintenance.
  • Potentially little benefit when an index has poor selectivity.

The better approach

Understand your actual query patterns.

For example, if your application frequently filters orders by status and creation date:

orders = Order.objects.filter(
    status="completed",
    date_created__gte=start_date
)

A composite index might be worth considering.

class Order(models.Model):
    status = models.CharField(max_length=20)
    date_created = models.DateTimeField()

    class Meta:
        indexes = [
            models.Index(
                fields=["status", "date_created"],
                name="order_status_created_idx"
            )
        ]

But don't blindly assume this index is optimal.

Use your database's query analysis tools, such as PostgreSQL's EXPLAIN ANALYZE, to understand the actual execution plan.

Consider selectivity, query frequency, table size and write patterns.

The lesson: Index for real query patterns, not assumptions.


8. Treating Background Processing as an Afterthought

The mistake

Consider an API endpoint that needs to send several emails, generate a PDF and call an external service.

It's tempting to perform everything synchronously inside the request.

def process_order_view(*, request):
    order = create_order(
        customer=request.user.customer
    )

    generate_invoice(order=order)
    send_confirmation_email(order=order)

    synchronise_external_system(
        order=order
    )

    return JsonResponse(
        data={"success": True}
    )

Why is it problematic?

The client has to wait for every operation to finish.

If one external service becomes slow or unavailable, the entire request is affected.

This also makes retry handling more difficult.

The better approach

Move suitable long-running or independently executable operations into background processing.

For example, using Celery:

def process_order_view(*, request):
    order = create_order(
        customer=request.user.customer
    )

    process_order_task.delay(
        order_id=order.id
    )

    return JsonResponse(
        data={
            "success": True,
            "order_id": order.id
        }
    )

The background task can handle the additional processing.

However, asynchronous processing introduces its own responsibilities:

  • Idempotency.
  • Retry policies.
  • Failure handling.
  • Task monitoring.
  • Transaction consistency.
  • Duplicate delivery protection.

Not every operation needs Celery. A simple application doesn't need distributed infrastructure just because asynchronous processing exists.

The lesson: Use background processing when the workload and business requirements justify it.


Final Thoughts

Django provides an excellent foundation for building applications, but knowing the framework's features is only part of the equation.

Understanding how those features behave under real-world conditions is what makes the difference.

A QuerySet isn't a list. A signal isn't necessarily visible to the code triggering it. A database transaction doesn't protect an external API call. And adding an index doesn't automatically make every query faster.

These details become increasingly important as applications grow.

The goal isn't to avoid every Django abstraction or introduce unnecessary architectural patterns.

It's to understand the implications of the decisions we make.

Good Django development isn't about writing more code. It's about making deliberate decisions that keep applications predictable, efficient and maintainable.