读写分离
在settings中配置不同名称的数据库连接参数,并配置一条数据库选择路由
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.sqlite3‘,
‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
},
‘db1‘: {
‘ENGINE‘: ‘django.db.backends.sqlite3‘,
‘NAME‘: os.path.join(BASE_DIR, ‘db1.sqlite3‘),
},
}
(1)第一种方法:
手动选择要使用的数据库
m1.UserType.objects.using(‘default‘).create(title=‘VVIP‘)
m2.Users.objects.using(‘db1‘).create(name=‘VVIP‘,email=‘xxx‘)
(2)方法二:
定义一下路由类,自动执行数据类
在seetings 中加入一条配置
DATABASE_ROUTERS = [‘db_router.Router1‘,]
class Router1: def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.model_name == ‘usertype‘: return ‘db1‘ else: return ‘default‘ def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ return ‘default‘
为读写操作指定类
这样在执行查询和修改时候就无需指定数据库
多应用分库
创建数据库时候执行指定的命令
# 第一步: python manage.py makemigraions # 第二步: app01中的表在default数据库创建 python manage.py migrate app01 --database=default # 第三步: app02中的表在db1数据库创建 python manage.py migrate app02 --database=db1
对数据库迁移和读写操作进行约束
class Router1: def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ if db==‘db1‘ and app_label == ‘app02‘: return True elif db == ‘default‘ and app_label == ‘app01‘: return True else: return False # 如果返回None,那么表示交给后续的router,如果后续没有router,则相当于返回True def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == ‘app01‘: return ‘default‘ else: return ‘db1‘
def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == ‘app01‘: return ‘default‘ else: return ‘db1‘