Django 数据库相关配置
Django 数据库相关配置
多个数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'db2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
},
}
数据库迁移
python manage.py makemigrations
python manage.py migrate -- database db2
读写分离
手动
stu_obj = models.Student.objects.using('default').all()
models.Student.objects.using('db2').create(name='xxx')
自动
# myrouter
class Router:
def db_for_read(self, model, **kwargs):
return 'default'
def db_for_write(self, model, **kwargs):
return 'db2'
在settings中配置
settings中配置
DATABASE_ROUTERS = ['myrouter.Router']
使用
stu_obj = models.Student.objects.all()
models.Student.objects.create(name='xx')
一主多从
# 一主多从
import random
class Router:
def db_for_read(self, model, **kwargs):
return random.choice(['db1', 'db2', 'db3'])
def db_for_write(self, model, **kwargs):
return 'db'
分库分表
# 分库分表
# app01 db1 app02 db2
class Router:
def db_for_read(self, model, **kwargs):
if model._meta.app_label == 'app01':
return 'db1 '
elif model._meta.app_label == 'app02':
return 'db2'
def db_for_write(self, model, **kwargs):
if model._meta.app_label == 'app01':
return 'db1 '
elif model._meta.app_label == 'app02':
return 'db2'
执行原生sql
from django.db import connection, connections
# cursor = connection.cursor()
cursor = connections['db2'].cursor()
cursor.execute("""SELECT * from app01_student """, )
row = cursor.fetchall()
print(row)