【问题标题】:Django Rest Framework multiples databasesDjango Rest Framework 多个数据库
【发布时间】:2019-02-22 22:19:46
【问题描述】:

我是 Django 新手,我正在尝试了解 Django 如何为我的应用程序使用两个数据库。

  • 数据库 1 - 我想用于 Django 系统

  • Database 2 是一个包含数据的现有数据库,我想让这些数据在我的 Django API 中可用,如下图所示:

Arquitetura da API

谢谢大家

【问题讨论】:

    标签: python django database django-rest-framework


    【解决方案1】:

    我用 DRF 和 django 来做这件事。 Use a database router

    这是我的路由器,不同数据库的每组模型都转到不同的文件。

    class DatabaseRouter(object):
        def module_switch(self,model):
    
            result = 'default'
            if model.__module__.endswith('foo_db1_models'): result = 'foo'
            if model.__module__.endswith('bar_db2_models'): result = 'bar'
            if model.__module__.endswith('baz_models'): result = 'baz'
            if model.__module__.endswith('grid_models'): result = 'grid'
            #print 'here', model.__module__, result, model.__class__.__name__
            return result
    
        def db_for_read(self, model, **hints):
            return self.module_switch(model)
    
        def db_for_write(self, model, **hints):
            return self.module_switch(model)
    
        def allow_relation(self, obj1, obj2, **hints):
            """
            Relations between objects are allowed if both objects are
            in the master/slave pool.
            """
            # db_list = ('master', 'slave1', 'slave2')
            # if obj1._state.db in db_list and obj2._state.db in db_list:
            #     return True
            return None
    
        def allow_migrate(self, db, app_label, model_name, **hints):
            """
            All non-auth models end up in this pool.
            """
            return True
    

    在 settings.py 中,您指定路由器:

    DATABASE_ROUTERS = ['my_proj_foo.db_router.DatabaseRouter']
    

    和其他数据库:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'db'
            'USER': 'foo',
            'PASSWORD': 'bar',
            'HOST': 'db.example.com',
            'PORT': '3306'
        },
        'bar': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'bar'
            'USER': 'foo',
            'PASSWORD': 'bar',
            'HOST': 'bar.example.com',
            'PORT': '3306'
        },
        'baz': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'baz',
            'USER': 'foo',
            'PASSWORD': 'bar',
            'HOST': 'baz.example.com',
            'PORT': '5432'
        },
    
       },
    

    【讨论】:

    • 感谢 ross,工作正常,对于 Microsoft Sql Server,我使用“django-pyodbc-azure”作为后端引擎。 (pip install django-pyodbc-azure)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2021-09-01
    • 2013-11-11
    • 2015-02-20
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多