多数据库操作

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'

猜你喜欢

转载自www.cnblogs.com/jassin-du/p/9052841.html