Database

Migrations

Use Django's migration system to manage database schema changes. Create migrations with python manage.py makemigrations and apply them with python manage.py migrate.

  • Keep migrations in each app's migrations/ folder.
  • Review generated migrations before applying to production.

Seeders & Fixtures

  • Use fixtures (.json, .yaml, .xml) for initial data loading with manage.py loaddata.
  • For custom seeding logic, use management commands or scripts.

Example:

python manage.py loaddata initial_data.json

Query Optimization

  • Use Django ORM for queries; prefer select_related and prefetch_related for related objects.
  • Avoid N+1 query problems by eager loading related data.
  • Use indexes for frequently queried fields.
  • Profile queries using Django Debug Toolbar or custom logging.

Example:

users = User.objects.select_related('profile').all()

Best Practices

  • Keep migrations atomic and reversible.
  • Document custom migration and seeding logic.
  • Test migrations and fixtures in development before production.
  • Regularly review and optimize queries for performance.