Routing System - Database Routing & URL Management
The routing system has two parts: a database router built from your DatabaseConfig entries,
and the URL integration that mounts django-cfg’s endpoints under /cfg/.
Database Routing
Routing apps to databases
Give a secondary DatabaseConfig an apps list. The generator collects apps from every database
into DATABASE_ROUTING_RULES ({app_label: alias}) and adds
django_cfg.routing.routers.DatabaseRouter to DATABASE_ROUTERS. Nothing is added when no
database has routing rules.
# api/config.py
from django_cfg import DjangoConfig, DatabaseConfig
class MyProjectConfig(DjangoConfig):
databases: dict[str, DatabaseConfig] = {
"default": DatabaseConfig.from_url("postgresql://user:pass@localhost:5432/main"),
"blog_db": DatabaseConfig.from_url(
"postgresql://user:pass@localhost:5432/blog",
apps=["blog"], # app labels, not dotted paths
),
"analytics_db": DatabaseConfig.from_url(
"postgresql://user:[email protected]:5432/analytics",
apps=["analytics"],
operations=["read"],
),
}apps takes Django app labels (blog, not apps.blog), because the router compares them with
model._meta.app_label. Feature configs such as GeoConfig(database="...") can add their own rules;
an explicit apps=[...] on a database wins over them.
What the router does
django_cfg.routing.routers.DatabaseRouter:
| Method | Behaviour |
|---|---|
db_for_read, db_for_write | Return the alias from DATABASE_ROUTING_RULES for the model’s app label; None (Django’s default) for unrouted apps |
allow_relation | If both objects are routed, only within the same database; if either is unrouted (for example User in default), allowed |
allow_migrate | A routed app migrates only on its alias; a non-routed app migrates on default when another app uses that alias |
Under manage.py test, an alias with test_mirror is redirected to its mirror source so everything
stays on one connection; this redirect is skipped outside tests.
operations is not enforced by the router
operations=["read"] is stored on DatabaseConfig (and exposed by matches_app, allows_operation),
but DatabaseRouter does not block writes. For a read-only database use a read-only database user, or
connect with a role that has no write rights.
Cross-database ForeignKeys between two routed apps on different aliases are rejected by allow_relation.
See Cross-database relations and Multi-database routing.
Usage
Routing is transparent:
from blog.models import Post
posts = Post.objects.all() # reads blog_db
post = Post.objects.create(title="New Post") # writes blog_db
Post.objects.using("default") # explicit alias still worksURL Management
Automatic URL integration
from django.urls import include, path
from django_cfg import add_django_cfg_urls, admin_urlpatterns
urlpatterns = [
path("api/", include("api.urls")),
*admin_urlpatterns(), # honours config.admin_access (enabled / path)
]
urlpatterns = add_django_cfg_urls(urlpatterns)add_django_cfg_urls appends the django-cfg URLs, the generated API client URLs for your
OpenAPIClientConfig groups, media serving, and (with DEBUG) static serving and
django_browser_reload.
admin_urlpatterns() also redirects GET/HEAD requests for the exact configured
admin root without its trailing slash (for example /admin to /admin/).
The redirect is temporary, non-cacheable and preserves query parameters.
Disabled or network-restricted admin routes remain hidden. Other routes and
unsafe methods are not automatically redirected: the REST API’s
OpenAPIClientConfig.append_slash=False default is unchanged.
Built-in URL patterns
django-cfg’s own apps are mounted by django_cfg.apps.urls:
/healthz, /healthz/live, /healthz/ready liveness and readiness probes
/healthz/drf/, /healthz/ready/drf/ the same, as DRF browsable pages
/cfg/endpoints/ endpoint status (JSON), /cfg/endpoints/drf/
/cfg/endpoints/urls/ URL list, /cfg/endpoints/urls/compact/
/cfg/commands/ management-command API
/cfg/accounts/, /cfg/totp/ sign-in and two-factor
/cfg/openapi/ OpenAPI generator endpoints
/cfg/sitemap/ sitemap sources
/cfg/monitor/ frontend monitor ingest
/cfg/mcp/ MCP endpoint
/cfg/admin/dashboard/ admin dashboard tabsConditional mounts: /cfg/geo/ (geo enabled), /cfg/analytics/ (AnalyticsConfig),
/cfg/chat/ (ChatConfig), /cfg/payments/ (PaymentsConfig).
URL information
from django_cfg import get_django_cfg_urls_info
info = get_django_cfg_urls_info()
info["django_cfg"]["prefix"] # "cfg/"
info["django_cfg"]["env_mode"]
info["django_cfg"]["version"]The dict has a django_cfg entry (version, prefix, site, docs and health URLs, env_mode, debug) and, when the
OpenAPI client is enabled, a django_client entry (groups, base URL, output dir).
Best Practices
1. Group apps by domain
"content_db": DatabaseConfig.from_url("...", apps=["blog", "cms"]),
"commerce_db": DatabaseConfig.from_url("...", apps=["shop", "orders", "payments"]),Keep related models together: relations across routed databases are not allowed.
2. Migrations follow the routing
migrate_to is validated (the alias must exist in databases), but DatabaseRouter.allow_migrate
does not read it: a routed app migrates on its own alias. Run manage.py migrate --database=<alias> per
alias, or manage.py migrate_all.
3. Test the routing
from django.test import TestCase
class RoutingTest(TestCase):
databases = {"default", "blog_db"}
def test_blog_routes_to_blog_db(self):
from blog.models import Post
post = Post.objects.create(title="Test")
self.assertEqual(post._state.db, "blog_db")Related Documentation
- Multi-database routing - Full routing guide
- Database configuration -
DatabaseConfigfields - Configuration Guide - Configure django-cfg
- CLI Tools - Command-line tools