Django ORM 數據庫設置和讀寫分離

1、Django的數據庫配置python

(一)修改settings.py文件關於數據庫的配置:mysql

  Django默認使用sqlite:web

# Django默認的數據庫庫,SQLit配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # sqlite引擎
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

  

  再添加一個數據庫:仿照「default」的格式直接添加:sql

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

 

注意:若是想要使用mysql,須要進行一下配置:數據庫

  1. 編輯項目文件夾下的settings.pydjango

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',  # mysql引擎
        'NAME': 'BookManagement',    
            # 數據庫名稱, 須要經過命令‘CREATE DATABASE BookManagement’在mysql命令窗口中提早建立
        'USER': 'root',   # 數據庫用戶名
        'PASSWORD': 'xxx', # 數據庫密碼 沒有密碼則爲空字符串
        'HOST': '', # 數據庫主機,留空默認爲localhost
        'PORT': '3306', # 數據庫端口
    }
}

  2. 編輯項目文件夾下的__init__.py : 因爲mysql在Django中默認驅動是MySQLdb, 而該驅動不適用於python3, 所以,咱們須要更改驅動爲PyMySQLapp

# 代碼實現:
import pymysql

pymysql.install_as_MySQLdb()

  3. 顯示SQL語句 ,前面咱們說了ORM是高層的面向對象的操做,轉換爲低層的SQL語句,若是想在終端打印對應的SQL語句,能夠在setting.py中加上日誌記錄dom

代碼實現:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

 

(二)、修改好數據庫配置以後,在models.py文件裏建立表,以後進行數據庫遷移工做:性能

python manage.py makemigrations  # 在migrations文件夾下生成記錄,遷移前檢查
python manage.py migrate  # 真正執行數據庫遷移命令,該命令執行以後建立表

 

2、讀寫分離網站

(一)手動讀寫分離

  1. 在使用數據庫時,經過.using(db_name)來手動指定要使用的數據庫

  優勢:不須要進行其他的配置,只須要經過.using(db_name)來手動指定要使用的數據庫就行。

  缺點:在大量的對數據庫進行操做以後,此種方法繁瑣

 

# 代碼實現
from django.shortcuts import HttpResponse
from . import models


def write(request):
    models.Products.objects.using('default').create(prod_name='熊貓公仔', prod_price=12.99)
    return HttpResponse('寫入成功')


def read(request):
    obj = models.Products.objects.filter(id=1).using('db2').first()
    return HttpResponse(obj.prod_name)

 

 

(二)自動讀寫分離

  經過配置數據庫路由,來自動實現,這樣就不須要每次讀寫都手動指定數據庫了。數據庫路由中提供了四個方法。這裏這裏主要用其中的兩個:def db_for_read()決定讀操做的數據庫,def db_for_write()決定寫操做的數據庫。

定義Router類

新建myrouter.py腳本,定義Router類:

class Router:
    def db_for_read(self, model, **hints):
        return 'db2'

    def db_for_write(self, model, **hints):
        return 'default'
配置Router

settings.py中指定DATABASE_ROUTERS

 

DATABASE_ROUTERS = ['myrouter.Router',]

一主多從方案

網站的讀的性能一般更重要,所以,能夠多配置幾個數據庫,並在讀取時,隨機選取,好比:

class Router:
    def db_for_read(self, model, **hints):
        """
        讀取時隨機選擇一個數據庫
        """
        import random
        return random.choice(['db2', 'db3', 'db4'])

    def db_for_write(self, model, **hints):
        """
        寫入時選擇主庫
        """
        return 'default'

分庫分表

在大型web項目中,經常會建立多個app來處理不一樣的業務,若是但願實現app之間的數據庫分離,好比app01走數據庫db1,app02走數據庫

class Router:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'app01':
            return 'db1'
        if model._meta.app_label == 'app02':
            return 'db2'

    def db_for_write(self, model, **hints):
       if model._meta.app_label == 'app01':
            return 'db1'
       if model._meta.app_label == 'app02':

參考博客:點這裏

default
相關文章
相關標籤/搜索