[Django]-Django utilizing/pulling data from other databases

4👍

First you will need a database router for your apps, I’ll try to do something similar to what you need with the information given

app1/routers.py

class App1Router(object):
    def db_for_read(self, model, **hints):

        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to app1.
        """
        if model._meta.app_label == 'app1':
            return 'default'
        return None
    def allow_relation(self, obj1, obj2, **hints):
         db_list = ('default', 'sap', 'sfdc')
        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=None, **hints):
        return True

and in your settings.py file add the following

DATABASE_ROUTERS = ['app1.routers.App1Router',]

You can use the inspectdb command to create the models of the existing databases, e.g.:

./manage.py inspectdb --database "sap"

I hope it helps

Source: Personal experience and the Django Documentation https://docs.djangoproject.com/en/1.10/topics/db/multi-db/

1👍

Django has support for multiple databases as described here:

https://docs.djangoproject.com/en/1.10/topics/db/multi-db/

Assuming you set your primary database as the main database, you will have to make sure to specify which database you want to access whenever you are reading from another database.

👤ubadub

1👍

The other answers have already mentioned the multi-DB nature of this and linked to the docs.

You may want to use something like the Django REST Frame to run access to the other tables as a mini-service for the rest of the app, rather than trying to context switch DB calls in your Views code.

E.g. if you need to lookup data in the SAP or SalesForce tables you make an Ajax request to your backend service with that ID. It will send you a JSON answer with whatever you need.

That way you can abstract the relationship and change implementation details in the future without having to rewrite a lot of code.

Leave a comment