1---2name: python-django3description: Write Python and Django code for Saleor — Django ORM patterns, signals, Celery tasks, type hints, migrations, management commands, and async views. Use when writing Python/Django in Saleor projects.4allowed-tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch5metadata:6 source: https://skillmd.com/skills/orcaqubits/python-django7---89# Python & Django for Saleor1011## Before writing code1213**Fetch live docs**:141. Web-search `site:docs.djangoproject.com topics models querysets` for current Django ORM documentation152. Web-search `site:docs.djangoproject.com topics signals` for Django signals reference163. Web-search `site:docs.celeryq.dev userguide tasks` for Celery task patterns and configuration174. Web-search `site:docs.saleor.io developer` for Saleor-specific Django conventions185. Fetch `https://docs.python.org/3/library/typing.html` for Python type hints reference1920## Django ORM Patterns for Saleor2122### QuerySet Operations2324| Operation | Method | Example Use |25|-----------|--------|-------------|26| **Filter** | `.filter(**kwargs)` | Filter products by type |27| **Exclude** | `.exclude(**kwargs)` | Exclude draft orders |28| **Annotate** | `.annotate(expr)` | Add computed fields (totals, counts) |29| **Aggregate** | `.aggregate(expr)` | Compute sum, avg across queryset |30| **Select related** | `.select_related("fk")` | Join foreign keys (avoid N+1) |31| **Prefetch related** | `.prefetch_related("m2m")` | Batch-load many-to-many (avoid N+1) |32| **Values** | `.values("field")` | Return dictionaries instead of objects |33| **Order by** | `.order_by("field")` | Sort results |3435### F and Q Objects3637| Object | Purpose | Example Use |38|--------|---------|-------------|39| `F("field")` | Reference model field in expressions | Update stock: `F("quantity") - 1` |40| `Q(condition)` | Complex lookups with OR/AND/NOT | `Q(status="active") | Q(featured=True)` |4142- Use `F()` for atomic field updates without race conditions43- Combine `Q()` objects with `|` (OR), `&` (AND), `~` (NOT) for complex filters4445## Model Relationships in Saleor4647| Relationship | Field Type | Example |48|-------------|-----------|---------|49| **One-to-Many** | `ForeignKey` | Order -> User, OrderLine -> Order |50| **Many-to-Many** | `ManyToManyField` | Product -> Category (via ProductCategory) |51| **One-to-One** | `OneToOneField` | User -> UserProfile |52| **Generic** | `GenericForeignKey` | Attribute values on multiple entity types |5354- Always set `on_delete` explicitly (`CASCADE`, `PROTECT`, `SET_NULL`)55- Use `related_name` for reverse lookups56- Index foreign keys used in frequent queries5758## Django Signals5960| Signal | Fires When | Common Use |61|--------|-----------|------------|62| `pre_save` | Before `model.save()` | Validate or transform data |63| `post_save` | After `model.save()` | Trigger side effects, send notifications |64| `pre_delete` | Before `model.delete()` | Clean up related resources |65| `post_delete` | After `model.delete()` | Remove cached data |66| `m2m_changed` | Many-to-many field modified | Update denormalized counters |6768- Saleor uses webhooks as the primary event mechanism, not Django signals69- Use signals sparingly for internal side effects only70- Never perform expensive I/O in signal handlers (use Celery tasks instead)71- Connect signals in `AppConfig.ready()` to avoid import issues7273## Celery Task Patterns7475### Defining Tasks7677| Pattern | Decorator | Use Case |78|---------|-----------|----------|79| **Shared task** | `@shared_task` | Framework-agnostic, recommended |80| **App task** | `@app.task` | Tied to specific Celery app |81| **Bound task** | `@shared_task(bind=True)` | Access `self` for retries |8283### Retry and Error Handling8485| Parameter | Description | Example |86|-----------|-------------|---------|87| `max_retries` | Maximum retry attempts | `3` |88| `default_retry_delay` | Seconds between retries | `60` |89| `retry_backoff` | Enable exponential backoff | `True` |90| `autoretry_for` | Exception classes to auto-retry | `(ConnectionError,)` |91| `acks_late` | Acknowledge after execution | `True` (prevents task loss) |9293- Pass serializable arguments (IDs, not model instances)94- Keep tasks idempotent — safe to retry without side effects95- Set reasonable timeouts with `soft_time_limit` and `time_limit`9697## Python Type Hints9899| Type | Import | Use |100|------|--------|-----|101| `Optional[T]` | `typing` | Value may be None |102| `list[T]` | Built-in (3.9+) | Typed list |103| `dict[K, V]` | Built-in (3.9+) | Typed dictionary |104| `Union[A, B]` | `typing` | Either type A or B |105| `Protocol` | `typing` | Structural subtyping (duck typing) |106| `TypedDict` | `typing` | Typed dictionary with fixed keys |107| `Literal["a", "b"]` | `typing` | Restrict to specific values |108109- Use `from __future__ import annotations` for postponed evaluation110- Type all function parameters, return values, and class attributes111- Use `mypy` or `pyright` for static type checking112113## Database Migrations114115| Command | Purpose |116|---------|---------|117| `python manage.py makemigrations` | Generate migration files from model changes |118| `python manage.py migrate` | Apply pending migrations to database |119| `python manage.py showmigrations` | List all migrations and their status |120| `python manage.py sqlmigrate app_name 0001` | Show SQL for a specific migration |121| `python manage.py squashmigrations app_name 0001 0010` | Combine multiple migrations |122123- Review generated migrations before applying to production124- Use `RunPython` for data migrations (separate from schema migrations)125- Test migrations on a copy of production data before deploying126127## Management Commands128129| Aspect | Convention |130|--------|-----------|131| **Location** | `app_name/management/commands/command_name.py` |132| **Class** | Subclass `BaseCommand` |133| **Entry point** | `handle(self, *args, **options)` method |134| **Arguments** | Use `add_arguments(self, parser)` with `argparse` |135| **Output** | Use `self.stdout.write()` and `self.style` |136137- Use management commands for one-off scripts, data fixes, and admin tasks138- Always add `help` text to commands for documentation139140## Async Django Views (ASGI)141142| Feature | Sync | Async |143|---------|------|-------|144| **View type** | `def view(request)` | `async def view(request)` |145| **Server** | WSGI (Gunicorn) | ASGI (Uvicorn, Daphne) |146| **ORM access** | Direct | Wrap in `sync_to_async` |147| **HTTP calls** | `requests` | `httpx` (async) |148149- Saleor runs via ASGI with Uvicorn workers under Gunicorn150- Django ORM is synchronous — use `sync_to_async` or `QuerySet.aiterator()`151- Use `httpx.AsyncClient` for non-blocking HTTP requests152153## Django Settings and Virtual Environments154155| Pattern | Description |156|---------|-------------|157| **Environment variables** | Load with `os.environ` or `django-environ` |158| **Split settings** | `settings/base.py`, `settings/dev.py`, `settings/prod.py` |159| **Twelve-Factor** | All configuration via environment variables |160161| Tool | Command | Notes |162|------|---------|-------|163| **venv** | `python -m venv .venv` | Built-in, standard |164| **poetry** | `poetry install` | Dependency resolution, lock file |165| **uv** | `uv venv && uv pip install -r requirements.txt` | Fast Rust-based installer |166167## Best Practices168169- Use `select_related` and `prefetch_related` to avoid N+1 query problems170- Keep Django signals lightweight — offload heavy work to Celery tasks171- Type all function signatures and use `mypy` for static analysis172- Make Celery tasks idempotent and pass only serializable arguments173- Review migration SQL before applying to production databases174- Use `F()` expressions for atomic field updates instead of read-modify-write175- Follow Saleor's existing code style when contributing to the core176- Use async views and `httpx` for I/O-heavy endpoints177- Store all configuration in environment variables following twelve-factor methodology178179Fetch the Python and Django documentation for current ORM patterns, Celery task configuration, and async view setup before implementing.