Andreias Stefan
Andreias Stefan

Reputation: 21

I can connect an application to 2 databases in Django?

I have a web application in Python django. I need to import users and display data about them from another database, from another existing application. All I need is the user to be able to login and display information about them. What solutions are?

Upvotes: 2

Views: 95

Answers (2)

Maxim Danilov
Maxim Danilov

Reputation: 3350

the answer from @NixonSparrow was wrong.

_meta.db_table defined only table_name in database and not the database self.

for switch database you can use manager.using('database_name'), for every model, it is good declared here: https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#topics-db-multi-db-routing

in my project i use multiple router. https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#topics-db-multi-db-routing

it help don't override every manager with using. But in your case:

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

and somethere in views:

other_users = otherUserModel.objects.using('other_users_data')

Probably, otherUserModel should define in meta, which table you want to use db_table = 'other_users_table_name' and also probably it should have managed=False, to hide this model from migration manager.

Upvotes: 1

NixonSparrow
NixonSparrow

Reputation: 6378

You can set 2 DATABASES in settings.py.

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

Then in one database store User models with authentication and stuff, in another rest information. You can connect information about specific User with a field that is storing id of User from another database.

If you have multiple databases and create a model, you should declare on which db it is going to be stored. If you didn't, it will be in default one (if you have it declared).

class UserModel(models.Model):
    class Meta:
        db_table = 'default'

class UserDataModel(models.Model):
    class Meta:
        db_table = 'user_data'

Upvotes: 4

Related Questions