Django + PostgreSQL连接-无法使用服务器端光标

时间:2018-09-27 12:58:10

标签: django python-3.x postgresql

我在PostgreSQL中有一个存储过程,该存储过程返回一个refcursor(其名称可以作为参数传递):

-- Example stored procedure....
CREATE OR REPLACE FUNCTION example_stored_procedure(ref refcursor, gid_number integer) RETURNS refcursor AS $$
DECLARE
ref refcursor;
BEGIN
 OPEN $1 for SELECT * FROM lucca_routes where gid = gid_number;
 RETURN $1;
END;
$$ LANGUAGE plpgsql;

然后,我可以从Postgres控制台以这种方式毫无问题地获得结果集:

BEGIN;
select example_stored_procedure('customcursor', 1);
FETCH ALL IN "customcursor";
COMMIT;

但是,我需要从Django应用程序内部获取结果集(使用其postgreSQL连接)。根据{{​​3}},我尝试过:

from django.db import connections
from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['GET'])
def testing_procedure(request):
    connection = connections['default']
    with connection.cursor() as cursor:
        cursor.execute("BEGIN")
        cursor.callproc("example_stored_procedure", ['customcursor', 1])
        # "steal" the cursor - ERROR HERE!
        cursor2 = connection.cursor('customcursor')
        # fetch here the data from cursor2...
        return Response(result)

当我尝试“窃取” callproc()返回的新光标(cursor2创建)时,出现错误:

TypeError:cursor()接受1个位置参数,但给出了2个

我做错了什么?如何从callproc()返回的refcursor中获取数据?

我正在使用 psycopg2 2.7.5

1 个答案:

答案 0 :(得分:1)

我根据@Alasdair的评论为以后的读者发布了解决方案。

您可以使用DatabaseWrapper对象中的函数create_cursor(self,name = None)使用服务器端游标。

在我的示例中:

def testing_procedure(request):
    connection = connections['default']
    with connection.cursor() as cursor:
        cursor.execute("BEGIN")
        cursor.callproc("example_stored_procedure", ['customcursor', 1])
        cursor2 = connection.create_cursor('customcursor')
        # fetch here the data from cursor2...
        result = cursor2.fetchall() # works!
        return Response(result)