如何在django db collection中自定义查询select数据库?

How to select database in django db collection custom query?

我的 Django 应用程序中有两个数据库。一个是默认的,另一个是次要的。当我尝试以下代码时,它总是 returns 来自默认数据库的数据。

from django.db import connection

def my_custom_sql(self):

cursor = connection.cursor()

cursor.execute("SELECT * FROM accounts_account where id=%s", [self.id])

row = cursor.fetchall()

return row

我想在第二个数据库中执行查询。

你只需要

from django.db import connections

而不是

from django.db import connection

并使用您的数据库别名如下:

cursor = connections['secondry_db'].cursor()