Chapter 5: Database Operations
5.1 Django Database Configuration
Supported Databases
Django officially supports multiple database backends:
- PostgreSQL - via
django.db.backends.postgresql - MySQL - via
django.db.backends.mysql - SQLite - via
django.db.backends.sqlite3 - Oracle - via
django.db.backends.oracle
Database Connection Configuration
Configure databases in settings.py:
python
# SQLite configuration example
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# PostgreSQL configuration example
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# MySQL configuration example
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}Configuration Parameter Explanation
- ENGINE: Database backend engine
- NAME: Database name (file path for SQLite)
- USER: Database username
- PASSWORD: Database password
- HOST: Database host address
- PORT: Database port
- OPTIONS: Additional database options
Multiple Database Configuration
Django supports configuring multiple database connections:
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'primary_db',
# ... other configurations
},
'read_replica': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'replica_db',
# ... other configurations
},
'analytics': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'analytics_db',
# ... other configurations
}
}Database Routing
For multiple database configurations, database routing can be used to control data read/write:
python
# Configure database routing in settings.py
DATABASE_ROUTERS = ['path.to.PrimaryReplicaRouter']
# Database routing example
class PrimaryReplicaRouter:
def db_for_read(self, model, **hints):
return 'read_replica'
def db_for_write(self, model, **hints):
return 'default'
def allow_relation(self, obj1, obj2, **hints):
return True
def allow_migrate(self, db, app_label, model_name=None, **hints):
return db == 'default'Environment Variable Configuration
In production environments, it's recommended to use environment variables to configure databases:
python
import os
from pathlib import Path
# Get configuration from environment variables
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DB_NAME', 'mydatabase'),
'USER': os.getenv('DB_USER', 'myuser'),
'PASSWORD': os.getenv('DB_PASSWORD', 'mypassword'),
'HOST': os.getenv('DB_HOST', 'localhost'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}Test Database Configuration
python
# Test environment database configuration
if 'test' in sys.argv:
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}Connection Pool Configuration
For production environments, consider using connection pooling:
python
# Using django-db-connections for connection pool configuration
DATABASES = {
'default': {
'ENGINE': 'django_db_connections.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
'OPTIONS': {
'pool_size': 20,
'max_overflow': 10,
'timeout': 30,
}
}
}Best Practices
- Use environment variables: Don't hardcode database credentials in code
- Use SQLite for development: Convenient for development and testing
- Use PostgreSQL for production: More powerful features and better performance
- Configure connection pooling: Improve database connection efficiency
- Regular backups: Ensure data security
- Monitor database performance: Use tools like Django Debug Toolbar
Common Problem Solutions
Connection timeout issue:
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
# ... other configurations
'OPTIONS': {
'connect_timeout': 10,
}
}
}Character set issue:
python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
# ... other configurations
'OPTIONS': {
'charset': 'utf8mb4',
'init_command': "SET NAMES 'utf8mb4'",
}
}
}Summary
Database configuration is an important foundation for Django applications:
- ✅ Supports multiple database backends (PostgreSQL, MySQL, SQLite, Oracle)
- ✅ Flexible single and multiple database configurations
- ✅ Protect sensitive information through environment variables
- ✅ Use database routing to implement read/write separation
- ✅ Configure connection pooling to improve performance
Proper database configuration can ensure the stability, security, and performance of applications.
Next
We will learn about Django's migration system and how to manage database schema changes.