我正在开发一个 Django 项目。我决定在 PostgreSQL 中编写逻辑代码,而不是用 Python 编写。因此,我在 PostgreSQL 中创建了一个存储过程。例如,存储过程如下所示:
create or replace procedure close_credit(id_loan int)
language plpgsql
as $$
begin
update public.loan_loan
set sum = 0
where id = id_loan;
commit;
end;$$
然后在settings.py中,我做了以下更改:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'pawnshop',
'USER': 'admin',
'PASSWORD': password.database_password,
'HOST': 'localhost',
'PORT': '',
}
}
那么问题来了,如何在views.py中调用这个存储过程呢?
p.s.
也许这听起来像是一个愚蠢的问题,但我确实在 Django 中找不到任何解决方案。
我建议将过程定义存储在迁移文件中。例如,在目录中myapp/migrations/sql.py
:
from django.db import migrations
SQL = """
create procedure close_credit(id_loan int)
language plpgsql
as $$
begin
update public.loan_loan
set sum = 0
where id = id_loan;
commit;
end;$$
"""
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [migrations.RunSQL(SQL)]
Note: 你需要更换myapp
与您的应用程序的名称,并且您需要包括only the 最近的您的应用程序的迁移文件作为依赖项。
现在您可以使用安装该过程python3 manage.py migrate
.
在数据库中定义过程后,您可以使用以下命令调用它cursor.callproc https://docs.djangoproject.com/en/3.2/topics/db/sql/#calling-stored-procedures:
from django.db import connection
def close_credit(id_loan):
with connection.cursor() as cursor:
cursor.callproc('close_credit', [id_loan])
话虽这么说,如果您的程序确实像您提供的示例一样简单,那么使用以下代码编写等效程序的维护成本会少得多ORM:
Loan.objects.filter(id=id_loan).update(sum=0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)