Django Rest Framework multiples databases

时间:2018-09-18 20:18:04

标签: python django database django-rest-framework

I'm new to Django and I'm trying to understand how Django can use two databases for my application.

  • Database 1 - I want to use to Django system

  • Database 2 is an existing database with data, and I want to make this this data available in my Django API, like the image below:

Arquitetura da API

Thanks all

1 个答案:

答案 0 :(得分: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'
    },

   },