Django-rest-framework – fetching data from another server's DB

Issue

I’ve implemented API using Django REST Framework that I use for my project which is a Flutter app.

*BUT, I want to add some data from another Server’s database, can I do it in Django REST Framework, and then include those in my API ?

Solution

You can set multiple databases in settings.py file.

DATABASES = {
    'default': {
        ...
    },
    'other': {
        ...
    }
}

And you need to create another app other and define the models in models.py of the newly created project folder. Let’s say, you defined a Sport model in other app.
Then in views.py file you can refer to this model.

from other.models import Sport

# in one of your api view
def SomeView(...):
    ...
    Sport.objects.using('other').create(...)

The main code is using('...').

Note: You don’t need to make migrations for the other app when you need to make migrations.
Hope it could help.

Answered By – David Lu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published