Django 数据库读写分离 分库分表

时间:2022-02-05 19:16:20

多个数据库

配置:

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, 'db.sqlite3'),
},
}
  • 写入到 指定数据库
python manage.py  makemigrations
python manage.py migrate -- database db2

使用

读写分离

  • 手动

s = models.Student.objects.using('default').all()

models.Student.objects.using('db2').create(name='xxx',)
  • 自动

  • settings中配置

    DATABASE_ROUTERS = ['myrouter.Router']

# 创建 myrouter.py 文件
# myrouter
class Router:
def db_for_read(self, model, **kwargs):
return 'default' def db_for_write(self, model, **kwargs):
return 'db2'

一主多从

# 一主多从
import random class Router:
def db_for_read(self, model, **kwargs):
return random.choices(['db1', 'db2', 'db3']) def db_for_write(self, model, **kwargs):
return 'db'

分库分表

# 分库分表  不同的app 使用不同的数据库

# 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)