Django Hacks 2026: 15 Insider Tricks & Error Fixes

Anurag Dadhich
1

Django hacks that tutorials skip but production teaches you the hard way. If you are a backend or full-stack developer (Django with React, Vue or Next.js), this guide covers 15 insider tricks, each with a real scenario, the error you will see, and the fix. Bookmark it before your next deploy.


1. N+1 Queries: The Silent Performance Killer

Scenario: Your API returns 50 orders with customer names. It is fast locally but takes 3 seconds in production, because every order triggers its own query (1 + 50 queries).


# Bad
for order in Order.objects.all():
    print(order.customer.name)      # one extra query per loop

# Good
Order.objects.select_related("customer")        # ForeignKey / OneToOne (JOIN)
Order.objects.prefetch_related("items")         # reverse FK / ManyToMany (2 queries)
Insider trick: Prefetch("items", queryset=Item.objects.filter(active=True), to_attr="active_items") gives you filtered prefetching. Add self.assertNumQueries(3) to your tests so nobody can reintroduce N+1 later.

2. Race Conditions: F() Expressions and select_for_update

Scenario: Two users buy the last ticket at the same time. Code like obj.stock = obj.stock - 1; obj.save() runs for both, and stock becomes -1.


from django.db import transaction
from django.db.models import F

# Simple counter: atomic at database level
Product.objects.filter(pk=pk, stock__gt=0).update(stock=F("stock") - 1)

# Complex logic: lock the row
with transaction.atomic():
    p = Product.objects.select_for_update().get(pk=pk)
    if p.stock < 1:
        raise ValueError("Out of stock")
    p.stock -= 1
    p.save()
Error: TransactionManagementError: select_for_update cannot be used outside of a transaction
Fix: always wrap it in transaction.atomic(). SQLite ignores row locks, so test on PostgreSQL or MySQL.

3. Celery Ran Before the Data Was Committed

Scenario: After signup you call send_welcome_email.delay(user.id). Sometimes the task fails with User matching query does not exist, because the worker picked it up before the transaction committed.


from django.db import transaction

def signup(request):
    with transaction.atomic():
        user = User.objects.create(...)
        transaction.on_commit(lambda: send_welcome_email.delay(user.id))
Rule: Anything that depends on committed data (tasks, webhooks, cache invalidation) belongs inside transaction.on_commit(). This matters even more with ATOMIC_REQUESTS=True.

4. Migration Errors and Real Fixes

4.1 Conflicting migrations

CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph

Two branches created migration 0005 independently. Fix it with:

python manage.py makemigrations --merge

4.2 Table already exists

django.db.utils.ProgrammingError: relation "app_table" already exists

The table exists in the database but Django does not know it. Run python manage.py migrate app 0005 --fake after checking showmigrations.

4.3 Adding a NOT NULL column to a huge table

Adding it directly can lock the table. Use three steps: (1) add the column with null=True, (2) backfill in batches using RunPython, (3) a separate migration setting null=False.

migrations.RunPython(fill_values, migrations.RunPython.noop)  # always provide reverse
Trick: Run python manage.py sqlmigrate app 0006 to see the exact SQL Django will execute before deploying.

5. Circular Imports

ImportError: cannot import name 'Order' from partially initialized module

orders/models.py and users/models.py import each other. Fixes:


# 1. String reference in ForeignKey
customer = models.ForeignKey("users.User", on_delete=models.CASCADE)

# 2. Lazy import inside a function
def get_total(self):
    from orders.models import Order
    ...

# 3. Resolve at runtime
from django.apps import apps
Order = apps.get_model("orders", "Order")

For the user model, always use settings.AUTH_USER_MODEL instead of importing it directly.

6. QuerySet Weapons Seniors Use


# exists() beats count() for a yes/no check
if Order.objects.filter(user=u).exists(): ...

# Fetch only what you need
User.objects.only("id", "email")
User.objects.values_list("email", flat=True)

# Save memory on millions of rows
for row in Big.objects.iterator(chunk_size=2000): ...

# Bulk operations (one query)
Item.objects.bulk_create(items, batch_size=500)
Item.objects.bulk_update(items, ["price"], batch_size=500)

# Conditional aggregation
from django.db.models import Count, Q
User.objects.annotate(paid=Count("orders", filter=Q(orders__status="paid")))

# Subquery
from django.db.models import OuterRef, Subquery
latest = Order.objects.filter(user=OuterRef("pk")).order_by("-created").values("total")[:1]
User.objects.annotate(last_total=Subquery(latest))
Debug trick: print(qs.query) shows the SQL, and qs.explain(analyze=True) (PostgreSQL) shows the query plan so you can spot missing indexes.

7. Signals and Bulk Operations

Scenario: An audit log was written in a post_save signal. Someone switched to bulk_create or queryset.update(), and the logs vanished. These methods do not call save() or send pre_save/post_save.

Advice: Do not hide critical business logic in signals. Create a service layer (services.py) and route all writes through it.

8. CSRF 403 and CORS with a React or Vue Frontend

403 Forbidden: CSRF verification failed. Request aborted. or blocked by CORS policy in the browser console

# settings.py (separate frontend domain)
INSTALLED_APPS += ["corsheaders"]
MIDDLEWARE.insert(0, "corsheaders.middleware.CorsMiddleware")

CORS_ALLOWED_ORIGINS = ["https://app.example.com"]
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = ["https://app.example.com"]   # scheme required (Django 4+)
SESSION_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

// axios
axios.defaults.withCredentials = true;
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken";

Use @ensure_csrf_cookie on a GET endpoint so the cookie is set first. A pure token-based JWT API (header only) does not need CSRF, but storing the token in a cookie brings it back.

9. Everything Broke After DEBUG=False

SymptomCauseFix
400 Bad Request, DisallowedHostDomain missing in ALLOWED_HOSTSALLOWED_HOSTS=["example.com","www.example.com"]
Static files 404Django does not serve static in productioncollectstatic plus WhiteNoise or Nginx
500 error, empty logsLOGGING not configuredAdd console/file logging and Sentry
Missing staticfiles manifest entryFiles not collectedRe-run collectstatic
Admin CSS brokenSame static issueSet STATIC_ROOT
Always run python manage.py check --deploy before release. It flags HSTS, secure cookie and SECRET_KEY problems.

10. The Classic Model Default Bug


# Wrong: evaluated once at server start
created = models.DateTimeField(default=timezone.now())

# Right: pass the callable
created = models.DateTimeField(default=timezone.now)
tags = models.JSONField(default=list)     # never default=[] (shared mutable)

Also remember: auto_now_add and auto_now fields are not editable in admin, and auto_now is not updated by QuerySet.update().

11. Django REST Framework Serializer Performance

Queries inside a SerializerMethodField create N+1 problems. Do the joins and annotations in get_queryset() and read the annotated value in the serializer.


class OrderViewSet(ModelViewSet):
    def get_queryset(self):
        return (Order.objects.select_related("customer")
                .prefetch_related("items")
                .annotate(item_count=Count("items")))

For large datasets use CursorPagination, because OFFSET gets slow on deep pages (offset 100,000). A dynamic ?fields=id,name serializer also keeps payloads small for the frontend.

12. Database Connections: "Too many clients"

OperationalError: FATAL: sorry, too many clients already

Every request opens a new connection. Set CONN_MAX_AGE = 60, or on Django 5.1+ use native pooling with "OPTIONS": {"pool": True}. Under heavy traffic add PgBouncer, and calculate gunicorn workers x connections against your database limit.

13. QuerySets Are Lazy: The Caching Game


qs = User.objects.all()
len(qs)        # query runs, results cached
qs[0]          # served from cache
qs.count()     # uses cache if loaded, else runs COUNT
bool(qs)       # loads the whole list; use exists() instead

In templates, {% if qs %} loads the entire list. Use .exists() or decide in the view.

14. Management Commands Seniors Quietly Use


python manage.py shell_plus --print-sql              # django-extensions: print every query
python manage.py diffsettings                        # what changed from defaults
python manage.py dbshell                             # direct database console
python manage.py showmigrations --plan               # migration order
python manage.py makemigrations --check --dry-run    # use in CI
python manage.py runserver_plus                      # Werkzeug debugger (local only)
python -X importtime manage.py check                 # find slow imports

Adding makemigrations --check to CI stops the classic "changed the model, forgot the migration" mistake from reaching production.

15. Small but Important Security Habits

  • Load SECRET_KEY and database passwords from environment variables.
  • Validate upload type and size, and serve media from a separate domain or bucket.
  • Never build raw SQL with f-strings: use cursor.execute("... WHERE id=%s", [uid]).
  • Change the default /admin/ URL and enable 2FA.
  • Use django-axes against brute force and DRF throttle_classes for APIs.

Quick Scenario Cheat Sheet

ProblemCheck first
Slow APIN+1, missing index, connection.queries
Random data mismatchRace condition, F(), select_for_update
Celery DoesNotExisttransaction.on_commit
Frontend POST returns 403CSRF trusted origins, cookies, CORS credentials
CSS missing after deploycollectstatic, WhiteNoise, STATIC_ROOT
Migration failureshowmigrations, --merge, --fake, sqlmigrate
Memory growingiterator(), only(), avoid loading huge lists

Frequently Asked Questions

How do I detect N+1 queries in Django?

Use django-debug-toolbar or shell_plus --print-sql, and add assertNumQueries() to your tests.

Why does my Celery task raise DoesNotExist?

The task starts before the database transaction commits. Call .delay() inside transaction.on_commit().

Why do I get a 403 CSRF error from my React app?

Check CSRF_TRUSTED_ORIGINS (with scheme), CORS_ALLOW_CREDENTIALS, axios withCredentials and the X-CSRFToken header.

Why are static files missing when DEBUG is False?

Django does not serve static files in production. Run collectstatic and serve them with WhiteNoise or Nginx.

Does bulk_create trigger signals?

No. bulk_create, bulk_update and queryset update() do not send post_save.

Conclusion

Django's real power shows when you understand its ORM, transactions and deployment behavior. These hacks come from years of production incidents, not from tutorials. Share this with your team and, in your next code review, check at least three things: N+1 queries, on_commit usage, and CSRF/CORS settings.

Which Django bug do you still remember? Tell me in the comments and it may become the next post.

  • Newer

    Django Hacks 2026: 15 Insider Tricks & Error Fixes

Post a Comment

1 Comments

  1. The on_commit example and the warning that bulk operations bypass signals are particularly useful together. Adding query-count assertions to tests also turns the N+1 advice into a regression check rather than a one-time optimisation.

    ReplyDelete
Post a Comment
To Top