gpt4 book ai didi

python - 在 Django 的 ORM 中访问存储过程的最佳方法是什么

转载 作者:IT老高 更新时间:2023-10-28 22:21:22 27 4
gpt4 key购买 nike

我正在设计一个相当复杂的数据库,并且知道我的一些查询将远远超出 Django 的 ORM 的范围。有没有人成功地将 SP 与 Django 的 ORM 集成?如果是这样,什么 RDBMS 以及您是如何做到的?

最佳答案

我们(musicpictures.com/eviscape.com)编写了该 django 片段,但并不是全部内容(实际上该代码当时仅在 Oracle 上测试过)。

当您想要重用经过验证和测试的 SP 代码时,或者当一次 SP 调用比多次调用数据库更快时,或者当安全​​性要求对数据库进行适度访问时,或者当查询非常复杂时,存储过程才有意义/多重步骤。我们正在对 Oracle 和 Postgres 数据库使用混合模型/SP 方法。

诀窍是让它易于使用并保持“django”的风格。我们使用 make_instance 函数获取游标的结果并创建从游标填充的模型的实例。这很好,因为游标可能会返回其他字段。然后你可以在你的代码/模板中使用这些实例,就像普通的 django 模型对象一样。

def make_instance(instance, values):
'''
Copied from eviscape.com

generates an instance for dict data coming from an sp

expects:
instance - empty instance of the model to generate
values - dictionary from a stored procedure with keys that are named like the
model's attributes
use like:
evis = InstanceGenerator(Evis(), evis_dict_from_SP)

>>> make_instance(Evis(), {'evi_id': '007', 'evi_subject': 'J. Bond, Architect'})
<Evis: J. Bond, Architect>

'''
attributes = filter(lambda x: not x.startswith('_'), instance.__dict__.keys())

for a in attributes:
try:
# field names from oracle sp are UPPER CASE
# we want to put PIC_ID in pic_id etc.
setattr(instance, a, values[a.upper()])
del values[a.upper()]
except:
pass

#add any values that are not in the model as well
for v in values.keys():
setattr(instance, v, values[v])
#print 'setting %s to %s' % (v, values[v])

return instance

# 像这样使用它:

pictures = [make_instance(Pictures(), item) for item in picture_dict]

# 这里有一些辅助函数:

def call_an_sp(self, var):
cursor = connection.cursor()
cursor.callproc("fn_sp_name", (var,))
return self.fn_generic(cursor)


def fn_generic(self, cursor):
msg = cursor.fetchone()[0]
cursor.execute('FETCH ALL IN "%s"' % msg)
thing = create_dict_from_cursor(cursor)
cursor.close()
return thing

def create_dict_from_cursor(cursor):
rows = cursor.fetchall()
# DEBUG settings (used to) affect what gets returned.
if DEBUG:
desc = [item[0] for item in cursor.cursor.description]
else:
desc = [item[0] for item in cursor.description]
return [dict(zip(desc, item)) for item in rows]

干杯,西蒙。

关于python - 在 Django 的 ORM 中访问存储过程的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/805393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com