Охватываемые темы: Supported Database Backends, Configuring SQLite (default), Configuring PostgreSQL, Via environment variable (recommended).
Supported Database Backends
Django supports several databases out of the box:
| Database | Package | Use case |
|---|---|---|
| SQLite | built-in | development |
| PostgreSQL | psycopg2 |
production |
| MySQL/MariaDB | mysqlclient |
production |
| Oracle | cx_Oracle |
enterprise |
Configuring SQLite (default)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Configuring PostgreSQL
pip install psycopg2-binary
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
Via environment variable (recommended)
pip install dj-database-url
import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='sqlite:///db.sqlite3',
conn_max_age=600,
)
}
.env:
DATABASE_URL=postgresql://user:pass@localhost/mydb
Multiple databases
DATABASES = {
'default': {'ENGINE': 'django.db.backends.postgresql', ...},
'analytics': {'ENGINE': 'django.db.backends.mysql', ...},
}
# Usage
Task.objects.using('analytics').all()
Why PostgreSQL for production
- Full transaction support
- JSON fields (
JSONField) - Full-text search
- Reliability and scalability
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!