Can we create a Rest Api in Django which can able to communicate with multiple databases(Relational, Non relational) dynamically. If yes please recommend me a way to do that

21 views
Skip to first unread message

anilkumar sangu

unread,
Jun 21, 2019, 11:25:50 AM6/21/19
to Django users
Hello,

I am working on Django

I have a scenario like 
I want to connect multiple databases. based on user selection.  if user selects MySql from front end my Api could able to connect MySql. if user select postgreSql my api could able to connect to postgreSql based on user selection dynamically. how to achieve this in Django Rest Api

Thanks in advance 

Chetan Ganji

unread,
Jun 21, 2019, 11:58:35 AM6/21/19
to django...@googlegroups.com
If it is one time selection like storing in a user level settings, you can store the database to use in user model 
i.e. you have to customize default Usermodel in django and add one extra field to store the db type of the current user. 

Then access the right db 
Author.objects.using(request.user.database).all() 
OR
Author.objects.using('mysql').all()
Author.objects.using('postgresql').all()
You might have to use the database routers also. It depends on your detailed requirements.


Official docs - 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/50a8fe84-0966-4b2c-bcf4-725f75a78609%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Andrew C.

unread,
Jun 23, 2019, 12:41:59 PM6/23/19
to django...@googlegroups.com
There really isn’t any point in doing that. 1) You should just use one of the two. Django officially supports Postgres. 2) You’d want to keep your users all jumbled in one database. If you have a foreign key to the username field, and the db can’t find a specific user because it’s in the other db, then what do you do then?

You wouldn’t need a REST api to do whatever your case is. Django supports using multiple database; just check their doc with a google search. It’s just a lot more business logic, and in my opinion, a lot more work and inefficiency.

--
Reply all
Reply to author
Forward
0 new messages