Skip to content

Commit

Permalink
django-stubs-ext: Add TypedDatabaseRouter as database router base cla…
Browse files Browse the repository at this point in the history
…ss (typeddjango#1522)

Base class for Django database routers. Django documentation:
https://docs.djangoproject.com/en/stable/topics/db/multi-db/#automatic-database-routing

Modeled after the TypedModelMeta feature

Co-authored-by: Adam Johnson <[email protected]>
  • Loading branch information
intgr and adamchainz authored Jun 6, 2023
1 parent c5a681d commit 6f5fbef
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ class MyModel(models.Model):
]
```

### Other typed base classes

* `django_stubs_ext.db.router.TypedDatabaseRouter` can be used as base when implementing custom database routers.

## FAQ

Expand Down
32 changes: 32 additions & 0 deletions django_stubs_ext/django_stubs_ext/db/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import TYPE_CHECKING, Optional, Type

if TYPE_CHECKING:
from typing import Any

from django.db.models import Model

class TypedDatabaseRouter:
"""
Typed base class for Django's DATABASE_ROUTERS setting. At runtime this is just an alias to `object`.
All methods are optional.
Django documentation: https://docs.djangoproject.com/en/stable/topics/db/multi-db/#automatic-database-routing
"""

def db_for_read(self, model: Type[Model], **hints: Any) -> Optional[str]:
...

def db_for_write(self, model: Type[Model], **hints: Any) -> Optional[str]:
...

def allow_relation(self, obj1: Type[Model], obj2: Type[Model], **hints: Any) -> Optional[bool]:
...

def allow_migrate(
self, db: str, app_label: str, model_name: Optional[str] = None, **hints: Any
) -> Optional[bool]:
...

else:
TypedDatabaseRouter = object

0 comments on commit 6f5fbef

Please sign in to comment.