1

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 Answer 1

1

I do this with DRF and django. Use a database router

This is my router where each set of models for a different database goes to a different file.

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

Inside of settings.py, you specify the router:

DATABASE_ROUTERS = ['my_proj_foo.db_router.DatabaseRouter']

and the other databases:

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

   },
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ross, working fine, and for Microsoft Sql Server i used "django-pyodbc-azure" to be the backend engine. (pip install django-pyodbc-azure).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.