python / expert
Snippet
Dynamic Asynchronous Database Router with Instance Hints
A custom database router that inspects instance-level hints to route read queries dynamically between primary and async replica databases.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from typing import Type, Optionalfrom django.db import modelsclass AsyncReplicaRouter:def db_for_read(self, model: Type[models.Model], **hints) -> str:if getattr(hints.get("instance"), "_use_primary", False):return "default"return "replica_async"def db_for_write(self, model: Type[models.Model], **hints) -> str:return "default"def allow_relation(self, obj1: models.Model, obj2: models.Model, **hints) -> Optional[bool]:db_set = {"default", "replica_async"}if obj1._state.db in db_set and obj2._state.db in db_set:return Truereturn None
django
Breakdown
1
class AsyncReplicaRouter:
Declares a custom database routing strategy class for multi-database Django applications.
2
def db_for_read(self, model: Type[models.Model], **hints) -> str:
Determines which database alias to route read operations to based on execution hints.
3
if getattr(hints.get("instance"), "_use_primary", False):
Checks model instance attributes to selectively bypass read replicas.
4
def allow_relation(self, obj1: models.Model, obj2: models.Model, **hints) -> Optional[bool]:
Evaluates whether foreign key relations are permitted across specified database aliases.