1. 程式人生 > >多數據庫操作

多數據庫操作

tle 數據 imp 做了 AI from hit RF mod

model。py

from django.db import models

class UserType(models.Model):
    title = models.CharField(max_length=32)

class UserInfo(models.Model):
    name = models.CharField(max_length=64)
    email = models.CharField(max_length=64)
    ut = models.ForeignKey(to=UserType)

命令

python3 manage.py makemigrations

# 指定到db1 數據庫裏面生成表結構 python3 manage.py migrate app01 --database=db1

方式一:手動

view。py

from django.shortcuts import render,HttpResponse
from app01 import models
def index(request):

    models.UserType.objects.using(db1).create(title=普通用戶)
  # 手動指定去某個數據庫取數據
    result = models.UserType.objects.all().using(
db1) print(result) return HttpResponse(...)

註意:

.using() 是queryset的方法,所以放在後面
models.UserType.objects   取出來是一個queryset對象

自動:添加配置文件 (讀寫分離)

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

再寫上配置

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, db.sqlite3),
    }
}
DATABASE_ROUTERS = [db_router.Router1,]
精進粒度 讀用戶類型表去db1, 讀用戶表去default
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 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

多數據庫操作