python / expert
Snippet
Django Management Command with Progress Bar and Styled Output
Django management commands provide a powerful way to interact with your application via the command line. This example demonstrates advanced features including chunked querysets for memory-efficient batch processing, progress bar visualization, dry-run mode for safe testing, and styled terminal output using Django's built-in color styles. These patterns are essential for data migration commands, bulk operations, and maintenance scripts.
snippet.py
1
from django.core.management.base import BaseCommand\nfrom django.core.management.color import no_style\nfrom django.db import connection\nfrom myapp.models import Product\n\nclass Command(BaseCommand):\n help = 'Rebuild product search index'\n\n def add_arguments(self, parser):\n parser.add_argument('--batch-size', type=int, default=500)\n parser.add_argument('--dry-run', action='store_true')\n\n def handle(self, *args, **options):\n batch_size = options['batch_size']\n dry_run = options['dry_run']\n total = Product.objects.count()\n\n self.stdout.write(self.style.SUCCESS(f'Starting indexing: {total} products'))\n self.stdout.write('---')\n\n processed = 0\n failed = 0\n\n for batch in self._chunked_queryset(Product.objects.all(), batch_size):\n for product in batch:\n try:\n self._index_product(product, dry_run)\n processed += 1\n except Exception as e:\n failed += 1\n self.stdout.write(\n self.style.ERROR(f'Failed: {product.sku} - {e}')\n )\n\n self._progress_bar(processed, total)\n\n self.stdout.write('')\n self.stdout.write(self.style.SUCCESS(\n f'Completed: {processed} indexed, {failed} failed'\n ))\n\n def _chunked_queryset(self, queryset, chunk_size):\n offset = 0\n while True:\n chunk = list(queryset[offset:offset + chunk_size])\n if not chunk:\n break\n yield chunk\n offset += chunk_size\n\n def _progress_bar(self, current, total):\n bar_length = 40\n percent = current / total if total else 1\n filled = int(bar_length * percent)\n bar = '█' * filled + '░' * (bar_length - filled)\n self.stdout.write(f'\r[{bar}] {current}/{total}', ending='')\n self.stdout.flush()
django
Breakdown
1
class Command(BaseCommand):
Base class providing standard Django management command infrastructure with argument parsing and output styling
2
parser.add_argument('--dry-run', action='store_true')
Boolean flag argument enabling safe test mode that performs all logic without persisting any database changes
3
for batch in self._chunked_queryset(...):
Memory-efficient iterator yielding sliced querysets to avoid loading millions of records into memory at once
4
self.style.ERROR() / self.style.SUCCESS()
Built-in terminal color styling helpers that automatically respect NO_COLOR env var and terminal capabilities