database

Django aggregation with annotate for statistics

Aggregation performs database-level calculations efficiently. I use aggregate() for single results across entire queryset (like average or total) and annotate() to add calculated fields to each object. Common aggregates include Count, Sum, Avg, Min, a

Django raw SQL queries for complex operations

For queries too complex for the ORM, I use raw SQL. The raw() method returns model instances. I use cursor.execute() for non-model queries. I always use parameterized queries to prevent SQL injection—never string interpolation. For reporting, raw SQL

Django ORM window functions for analytics

Window functions perform calculations across rows related to the current row. I use them for running totals, rankings, and moving averages. Django's Window expression with functions like RowNumber, Rank, DenseRank provide SQL window function support.

Django Q objects for complex queries

Q objects enable complex query logic with OR, AND, and NOT operations. I combine them with | for OR and & for AND. The ~Q() syntax negates a condition. This is cleaner than raw SQL for dynamic filters. I build Q objects conditionally based on user

Django transaction handling with atomic decorator

Database transactions ensure data integrity when multiple operations must succeed or fail together. I use @transaction.atomic on views or functions to wrap them in a transaction. For partial rollbacks, I use transaction.atomic() as a context manager a

Django atomic transactions for data integrity

The atomic decorator/context manager ensures all-or-nothing database operations. I wrap related operations in @transaction.atomic or with transaction.atomic() blocks. If any operation fails, the entire transaction rolls back. This prevents partial dat

Django JSON field for flexible schema data

JSONField stores structured data without creating separate tables. I use it for settings, metadata, or varying attributes. Django provides database-level JSON operations via lookups like __contains, __has_key. For PostgreSQL, I get native JSON operato

Django bulk operations for performance

Bulk operations reduce database round-trips dramatically. I use bulk_create() for inserting many objects at once, bulk_update() for updates, and update() for queryset-level updates. These bypass save() methods and signals for speed. For large datasets

Django database migrations best practices

Migrations track database schema changes. I use makemigrations after model changes and review generated migrations. For data migrations, I create empty migrations with makemigrations --empty and write RunPython operations. I test migrations on dev dat

Django database read-write split with routers

Database routers enable read-write splitting for scaling. I direct reads to replicas and writes to primary. The router examines hints and model to make routing decisions. For read-heavy apps, this distributes load across multiple databases. I use usin

Django query optimization with only and defer

The only() method loads specified fields only, while defer() excludes specified fields. This reduces data transfer and memory usage. I use only() when I need just a few fields from large models. For read-only displays, this prevents loading unnecessar

Django database connection pooling for performance

Connection pooling reuses database connections instead of creating new ones per request. I use django-db-pool or configure persistent connections with CONN_MAX_AGE. This reduces connection overhead significantly. For high-traffic sites, I set appropri