MENU

Catalog

    django中数据读写分离

    February 23, 2019 • python阅读设置

    方式一:是视图里面用using方式可以进行指定到哪个数据读写

    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('...')
    
    

    方式二:写配置文件

    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',]
    最后编辑于: June 16, 2019
    Leave a Comment