kku*_*sik 25 python sql django stored-procedures django-models
我正在设计一个相当复杂的数据库,并且知道我的一些查询将远远超出Django的ORM范围.有没有人成功地将SP与Django的ORM集成在一起?如果是这样,什么是RDBMS,你是怎么做到的?
小智 23
我们(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
Run Code Online (Sandbox Code Playgroud)
#像这样使用它:
pictures = [make_instance(Pictures(), item) for item in picture_dict]
Run Code Online (Sandbox Code Playgroud)
#这里有一些辅助函数:
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]
Run Code Online (Sandbox Code Playgroud)
欢呼,西蒙.
igo*_*gue 16
您必须在Django中使用连接实用程序:
from django.db import connection
cursor = connection.cursor()
cursor.execute("SQL STATEMENT CAN BE ANYTHING")
Run Code Online (Sandbox Code Playgroud)
然后你可以获取数据:
cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)
要么:
cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)
更多信息:http://docs.djangoproject.com/en/dev/topics/db/sql/
别。
严重地。
将存储过程逻辑移到它所属的模型中。
将一些代码放在 Django 中,将一些代码放在数据库中是维护的噩梦。在我 30 多年的 IT 工作中,我花了太多时间试图清理这种烂摊子。
小智 5
有一个很好的例子:https : //djangosnippets.org/snippets/118/
from django.db import connection
cursor = connection.cursor()
ret = cursor.callproc("MY_UTIL.LOG_MESSAGE", (control_in, message_in))# calls PROCEDURE named LOG_MESSAGE which resides in MY_UTIL Package
cursor.close()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30079 次 |
最近记录: |