简体   繁体   English

来自另一台主机的 Django REST 框架 sql 原始查询

[英]Django rest framework sql raw query from another host

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.第一个数据库是主数据库,我想在views.py(请求)下从第二个数据库查询数据我现在使用Django RestFrameworks。 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')

如果您有多个数据库,则可以using的方法查询所需的数据库,只需传递所需数据库的名称,例如:

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

The Django documentation goes into detail on how to use multiple databases: Django 文档详细介绍了如何使用多个数据库:

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

I would also recommend using the Django ORM rather than raw SQL queries:我还建议使用 Django ORM 而不是原始 SQL 查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM