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'),
    },
}

  迁移 migrate --databse db2

二、读写分离

  手动读写:

# 写入数据库 use using
models.Student.objects.using('db2').create(name='xxxx')

# 读取数据库
ret = models.Student.objects.using('default').all()


# 读取数据库
ret = models.Student.objects.using('default').all()


for i in ret:
    i.name = 'wl'
    i.save(using='default')

  自动配置读写:

  在项目中创建router文件:app01-> router

class Router:
    def db_for_read(self, model, **kwargs):
        return 'default'

    def db_for_write(self, model, **kwargs):
        return 'db2'

  settings.py文件配置

DATABASE_ROUTERS = ['app01.router.Router']

三、一主多从

  写入一个数据中,从多个数据库读取

# 一主多从
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 'default'

四、分库分表

  app01的表放在db1

  app02的表放在db2

# 分库分表

class Router:
    def db_for_read(self, model, **kwargs):
        label = model._meta.app_label

        if label == 'app01':
            return 'db1'
        elif label == 'app02':
            return 'db2'

    def db_for_write(self, model, **kwargs):
        label = model._meta.app_label

        if label == 'app01':
            return 'db1'
        elif label == 'app02':
            return 'db2'

  model:

model._meta.app_label   app名称
model._meta.model_name    model名称

 

posted @ 2019-09-20 09:43  WiseAdministrator  阅读(209)  评论(0编辑  收藏  举报