0
votes

I need to developed Django rest API with access to multiple databases and also need to authenticate from multiple databases

ex -

user1 - authenticate from database1 user table user2 - authenticate from database2 user table

router URL ex -

http://examle.com/API/auth/{site1}/login - this route should use database1 user table username and password http://example.com/API/auth/{site2)/login - this route should use database2 user table username and password

how can I achieve this task?

1
In your case, you have to try - with connection('db-name') to perform your queries. However, I think you are developing a multi-tenant SAAS app. If that is true, I would suggest that there are better ways (like muti-tenant setups) to achieve this rather than using different databases. - Arvind Kumar

1 Answers

0
votes

There are so many ways you could do this but i Suggest you to use two different model for each table in databases, for example let's call them User1 and User2.

Depending on how you implement login and User model in your django app, you can define these two models in your application, inheriting from from django.contrib.auth.models.AbstractUser. (Solutions like this maybe not suit well for you, because this wants to create a foreign key in database to auth_user table that is created by django itself. This will trouble you because you are using 2 different tables and I guess inheriting model and have its fields in your own model (that makes having its columns in your own table) will be a better solution for you.)

After defining two models, you need to connect to two different databases and authenticate user in your app. For this I suggest you to read this article by django that explains how to connect to multiple databases and how to route them (meaning when to connect each one of them.)

After having two models and connecting to them in your app, you just need to customize your authentication. It depends on how you have implemented you login and authentication in those urls and views you mentioned above. If you just need to access your models and you can check credentials by yourself, you are already done because you know how to access each model already. If you are using django functions to login, I suggest you to read this part of article, and implement any customization by yourself.

For more information and details, you need to give information about how you are implementing authentication but i guess those will be another questions.