python - cursor.fetchall() 只返回函数游标的默认值(不运行 fetch all in)

标签 python sql django postgresql

我在尝试通过我在数据库中创建的函数(使用 postgresql + postgis)提取数据时遇到了一些麻烦。情况是,每当我运行我的查询时,它可以通过 sql 在我的函数中单独找到,它运行得很好并返回我的数据。

我的函数是这样的

CREATE OR REPLACE FUNCTION common.myfunc(string) RETURNS refcursor AS 
    $BODY$ 
    DECLARE
         ref refcursor default 'outrefcursor' 
    BEGIN
         OPEN ref FOR

         -- pretty big query here

         RETURN ref; END;
    $BODY$   LANGUAGE plpgsql VOLATILE

当我运行时

SELECT common.myfunc(string);
FETCH ALL IN outrefcursor;

一切正常

但是,当我这样做时,在我的 django 方面

cursor.execute("SELECT * FROM common.myfunc(someString)")
mydata = cursor.fetchall()

返回游标的默认值 fetchall() behavior

如果能帮助我解决这种奇怪的行为,我将不胜感激

最佳答案

解决了。交易是:如果您需要运行一个 sql 函数,然后 fetch all in cursor,您必须显式地和原子地执行它。

例如,

你运行你的函数

SELECT common.myfunc(string);
FETCH ALL IN outrefcursor;

首先,django 的 cursor.fetchall() 不会为您执行 FETCH ALL ---。它必须是明确的命令。但是,如果您运行 cursor.execute("SELECT * FROM common.myfunc(someString)"),django 将自动提交此命令并失去对从查询返回的游标的跟踪。诀窍是用 @transaction.atomic

包裹你的 View

按照例子,

@transaction.atomic
def func(request):
cursor = connection.cursor()
    try:
        cursor.execute("SELECT myfunc('"+ parameter +"')")
        cursor.execute('FETCH ALL IN "outrefcursor"')
        data = cursor.fetchall()
    finally:
        cursor.close()

关于python - cursor.fetchall() 只返回函数游标的默认值(不运行 fetch all in),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028843/

相关文章:

sql - rails 参与!错误(无法批量分配 protected 属性 : user)

SQL 触发器编译但出现错误

python - 如何从 Emacs 运行 django shell?

python - 多行正则表达式 python

sql - Django:如何正确删除数据库记录以防止主键重用?

python - 无法获得 tensorflow DNNClassifier 的预测

python - django 使用扩展用户配置文件加入 auth_user

python - 更改模型管理表单默认值

python - 如何在散点自动放置的箭头上注释点

python - Django formset,查询每个表单的关系字段