Database Models
Django-CFG provides Pydantic models for type-safe database configuration.
DatabaseConfig
Type-safe database connection configuration with validation.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
engine | str | None | None | Django database engine (auto-detected from URL scheme if not provided) |
name | str | required | Database name or connection string |
user | str | None | None | Database user |
password | str | None | None | Database password (hidden in repr) |
host | str | "localhost" | Database host |
port | int | 5432 | Database port (1-65535) |
connect_timeout | int | 10 | Connection timeout in seconds (≥1) |
sslmode | str | "prefer" | SSL mode for connection |
options | dict[str, Any] | {} | Additional database-specific options |
conn_max_age | int | 0 | Maximum age of database connections in seconds (must be 0 with connection pooling) |
conn_health_checks | bool | True | Enable database connection health checks |
apps | list[str] | [] | Django app labels that should use this database |
operations | list[str] | ["read", "write", "migrate"] | Allowed operations for this database |
migrate_to | str | None | None | Override database alias for migrations |
routing_description | str | "" | Human-readable description of the routing rule |
atomic_requests | bool | None | None | Wrap each HTTP request in a transaction (defaults True for default, False for secondary) |
test_mirror | str | None | None | Mirror this database to another alias during tests |
Methods
| Method | Returns | Description |
|---|---|---|
to_django_config() | dict[str, Any] | Convert to Django database configuration format |
Validation
- Port range: 1-65535
- Timeout: ≥1 second
- Engine: Optional — auto-detected from URL scheme when using
from_url() - Connection string parsing:
DatabaseConfig.from_url()supportspostgresql://,mysql://,sqlite:///formats
Usage Examples
SQLite Configuration
from django_cfg import DjangoConfig, DatabaseConfig
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = True
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.sqlite3',
name='db/default.sqlite3'
)
}Generated Django settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db/default.sqlite3',
'OPTIONS': {},
# plus CONN_MAX_AGE, CONN_HEALTH_CHECKS, DISABLE_SERVER_SIDE_CURSORS
}
}PostgreSQL Configuration
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='production_db',
user='dbuser',
password='secure_password',
host='db.example.com',
port=5432,
sslmode='require',
connect_timeout=30
)
}Generated Django settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'production_db',
'USER': 'dbuser',
'PASSWORD': 'secure_password',
'HOST': 'db.example.com',
'PORT': 5432,
'OPTIONS': {
'connect_timeout': 30,
'sslmode': 'require',
}
}
}MySQL Configuration
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.mysql',
name='myapp_db',
user='root',
password='mysql_password',
host='localhost',
port=3306,
options={
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
)
}Multi-Database Configuration
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='users_db',
user='dbuser',
password='password',
host='localhost'
),
'blog_db': DatabaseConfig(
engine='django.db.backends.postgresql',
name='blog_db',
user='dbuser',
password='password',
host='localhost'
),
'shop_db': DatabaseConfig(
engine='django.db.backends.postgresql',
name='shop_db',
user='dbuser',
password='password',
host='localhost'
)
}Routing Apps to a Database
There is no separate routing-rule class. Routing is part of DatabaseConfig: the
apps, operations, migrate_to and routing_description fields describe which
Django apps use that database. django-cfg builds the database router from them.
| Field | Default | Description |
|---|---|---|
apps | [] | App labels routed to this database |
operations | ["read", "write", "migrate"] | Declared operations (not enforced by the router; use a read-only DB user for read-only access) |
migrate_to | None | Alias that must exist in databases (validated; the router does not use it to move migrations) |
routing_description | "" | Human-readable note |
Helper methods: matches_app(app_label), allows_operation(operation),
get_migration_database() and has_routing_rules().
Basic Routing
from django_cfg import DjangoConfig, DatabaseConfig
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='users_db',
user='dbuser',
password='password',
host='localhost'
),
'blog_db': DatabaseConfig(
engine='django.db.backends.postgresql',
name='blog_db',
user='dbuser',
password='password',
host='localhost',
apps=['blog'],
routing_description='Route blog app to blog_db',
),
}Advanced Routing
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='users_db',
user='dbuser',
password='password',
host='localhost'
),
'shop_db': DatabaseConfig(
engine='django.db.backends.postgresql',
name='shop_db',
user='dbuser',
password='password',
host='localhost',
apps=['shop', 'payments'],
),
# Read-only analytics database
'analytics_db': DatabaseConfig(
engine='django.db.backends.postgresql',
name='analytics_db',
user='readonly',
password='password',
host='analytics-server',
apps=['analytics'],
operations=['read'],
),
}See Multi-Database Routing for the full routing guide.
Environment-Specific Configuration
Build the databases dict from environment variables, so one config serves every
environment:
import os
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
databases: dict = {
'default': DatabaseConfig.from_url(
os.environ.get('DATABASE_URL', 'sqlite:///db/dev.sqlite3')
),
}Connection String Parsing
DatabaseConfig can parse connection URLs:
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
databases: dict = {
'default': DatabaseConfig.from_url('postgresql://user:pass@localhost/dbname')
}Supported formats:
- PostgreSQL:
postgresql://user:pass@host:port/dbname - MySQL:
mysql://user:pass@host:port/dbname - SQLite:
sqlite:///relative/db.sqlite3(relative path) orsqlite:////abs/path/db.sqlite3(absolute path, four slashes)
Security Best Practices
1. Use Environment Variables
import os
class MyConfig(DjangoConfig):
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name=os.getenv('DB_NAME', 'default_db'),
user=os.getenv('DB_USER', 'dbuser'),
password=os.getenv('DB_PASSWORD'),
host=os.getenv('DB_HOST', 'localhost')
)
}2. Enable SSL in Production
class MyConfig(DjangoConfig):
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='production_db',
user='prod_user',
password=os.getenv('DB_PASSWORD'),
host='prod-db.example.com',
sslmode='require', # Enforce SSL
options={
'sslrootcert': '/path/to/ca-cert.pem'
}
)
}3. Set Connection Timeouts
class MyConfig(DjangoConfig):
databases: dict = {
'default': DatabaseConfig(
engine='django.db.backends.postgresql',
name='production_db',
user='prod_user',
password=os.getenv('DB_PASSWORD'),
host='prod-db.example.com',
connect_timeout=30, # 30 second timeout
)
}Validation
DatabaseConfig validates:
- Port range (1-65535)
- Timeout (≥1 second)
- Connection string format
- Required fields (
nameonly;engineis optional and auto-detected from URL)
Example validation error:
# ❌ Invalid port
DatabaseConfig(
engine='django.db.backends.postgresql',
name='mydb',
port=99999 # Validation error: port must be ≤ 65535
)See Also
- Database Overview - Database configuration guide
- DjangoConfig - Base configuration class