Home > OS >  Django rest framework sql raw query from another host
Django rest framework sql raw query from another host

Time:07-12

I have two database with different connection, 1st is the default database and 2nd is for data only.

1st DB:

Host:0.0.0.0
port:5822
dbname:DBone
user:postgres
password:user:postgres

2nd DB:

Host:0.0.0.0
port:5842
dbname:DBtwo
user:postgres
password:user:postgres

1st database the main database, I want to query data from 2nd database under views.py (request) Im using Django RestFrameworks now. I want to raw query from another host connection, how to do that?

@api_view(['GET'])
def get_data(request):
    data = DBtwo.objects.raw(SELECT current from DBtwo WHERE name ='Test' AND gender ='M' AND age ='20')

CodePudding user response:

If you have multiple databases, then you can query the needed one with a method using, simply pass the name of the database you need, e.g.:

DBtwo.objects.using(<DB_NAME>).raw(<RAW SQL QUERY>)

CodePudding user response:

The Django documentation goes into detail on how to use multiple databases:

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

I would also recommend using the Django ORM rather than raw SQL queries:

https://docs.djangoproject.com/en/4.0/topics/db/sql/

  • Related