如何在 Django 后端使用存储过程?

How to use stored procedures with Django backend?

我已经在 SSMS 中为查询 SELECT * FROM TABLE 创建了一个存储过程,现在我想创建一个 Django API 并对其进行测试。整个过程是怎样的?

我的脚本来自 SQL 存储过程:

USE [test]
GO
/****** Object:  StoredProcedure [dbo].[spGetAll]     ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[spGetAll] 
    
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * from app_comment
END
GO

为了调用存储过程,请执行以下操作-

from django.db import connection

def dictfetchall(cursor):
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

with connection.cursor() as cursor:
    cursor.callproc("stored_procedure", [arg1, arg2, arg3])
    data = dictfetchall(cursor)

供参考查看docs

我无法使 alamshafi2263 的答案生效,给出了各种语法错误。我的程序接受一个参数,但 returns 没有值。 这是我成功使用的:

from django.db import connection
local_cursor = connection.cursor()
call_definition = f'call public.ap_update_holding_value({transaction_id})'
local_cursor.execute(call_definition)

上面的transaction_id是参数值。 使用 Django==3.1.13 测试,psycopg2==2.9.1