【问题标题】:How to select database in django db collection custom query?如何在 django db 集合自定义查询中选择数据库?
【发布时间】: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()

返回行

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

【问题讨论】:

标签: python mysql django database psql


【解决方案1】:

你只需要

from django.db import connections

而不是

from django.db import connection

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2012-07-17
    相关资源
    最近更新 更多