如何在 django db 集合自定义查询中选择数据库?

Posted

技术标签:

【中文标题】如何在 django db 集合自定义查询中选择数据库?【英文标题】:How to select database in django db collection custom query? 【发布时间】:2017-12-30 10:15:39 【问题描述】:

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

从 django.db 导入连接

def my_custom_sql(self):

cursor = connection.cursor()

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

row = cursor.fetchall()

返回行

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

【问题讨论】:

Django, multiple databases with raw sql. How to choose db?的可能重复 Django multiple and dynamic databases的可能重复 【参考方案1】:

你只需要

from django.db import connections

而不是

from django.db import connection

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

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

【讨论】:

以上是关于如何在 django db 集合自定义查询中选择数据库?的主要内容,如果未能解决你的问题,请参考以下文章