在django中实现数据库读写分离,基于setting文件的配置以及自定义模块实现

 

先创建多个App应用如图:

demo1里面的model(就只有model里面有内容其余都为空):

from django.db import models

# Create your models here.
class Employee(models.Model):
    name=models.CharField(max_length=32)
    age=models.IntegerField()
    department_id=models.ForeignKey(to='Department')


class Department(models.Model):
    name=models.CharField(max_length=32)

 

demo2中的model:

from django.db import models

# Create your models here.
class Actors(models.Model):
    name=models.CharField(max_length=32)
    gender=models.BooleanField(blank=True,null=False)

 

demo3中的model:

from django.db import models

# Create your models here.
class Class(models.Model):
    name=models.CharField(max_length=32)

 

db_router.py这里是读写分离的配置模块,自定义的

class Router:
    def db_for_writer(self, model, **hints):
        if model._meta.model_name == 'class':
            return 'db3'
        else:
            return 'default'

    def db_for_read(self, model, **hints):
        # if model._meta.model_name=='class':
        return 'db3'

 

setting配置文件:

"""
Django settings for s8day141 project.

Generated by 'django-admin startproject' using Django 1.11.9.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mx@9%r5ax3-*8i*fjm+9(^h^ybco1_7(8*m_!yhojtcgwe=#is'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'demo1.apps.Demo1Config',
    'demo2.apps.Demo2Config',
    'demo3.apps.Demo3Config',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 's8day141.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 's8day141.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
# 这里是数据库配置,我们建立了多个sqlite数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  # 值得注意的是这里的base_DIR后面的字符串才是数据库的名字
    },
    'test': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'test.sqlite3'),
    },
    'db3': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db3.sqlite3'),
    }
}
DATABASE_ROUTERS = ['db_router.Router', ]  # 这里的db_router是我们的py文件名,
# 后面的Router是该文件里面的类名
# Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'

 

posted @ 2018-06-04 11:30  dream-子皿  阅读(111)  评论(0)    收藏  举报