python / expert
Snippet
Multi-Database Query Routing with Custom Error Handling Hooks
Django query routers allow customizing multi-database selection dynamically based on hints. Raising structured keys when contextual metadata is missing prevents unintended reads against default storage backends.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class TenantDatabaseRouter:"""Routes read/write operations and manages fallback errors."""def db_for_read(self, model, **hints):tenant = hints.get("tenant_id")if not tenant:raise KeyError("Missing tenant_id hint in query routing context")return f"tenant_{tenant}"def db_for_write(self, model, **hints):return self.db_for_read(model, **hints)def allow_relation(self, obj1, obj2, **hints):return obj1._state.db == obj2._state.dbdef allow_migrate(self, db, app_label, model_name=None, **hints):return db.startswith("tenant_")
django
Breakdown
1
def db_for_read(self, model, **hints):
Interceptor method invoked by Django ORM before forming database read connections.
2
tenant = hints.get("tenant_id")
Extracts routing parameters passed through queryset hints context.
3
if not tenant: raise KeyError(...)
Enforces strict parameter presence by halting execution when routing hints are omitted.
4
return obj1._state.db == obj2._state.db
Ensures foreign key relations only link models residing within the exact same database database target.