python - Django Rest Framework 多个数据库

标签 python django database django-rest-framework

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

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

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

Arquitetura da API

谢谢大家

最佳答案

我用 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'
    },

   },

关于python - Django Rest Framework 多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394035/

相关文章:

python - 在 python 中列出转换的字符串?

python - 使用 BeautifulSoup 检查 html 页面是否不包含特定字符串

python - 使用名为 "pk"的 URL 关键字参数调用预期 View

c# - 为什么我的 C# 中的 SQL 代码不起作用?

sql - Oracle Trigger If 语句条件以某种方式未被满足?

python - 在 Django 中将表分为两部分

python - 是否可以跨多个文件共享命名空间

python - 如何以 Numpydoc 格式记录多个返回值?

python - Django 通过一个表获取数据并过滤一组相关对象

javascript - 使用 Django 提交时关闭 Bootstrap Modal