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

时间:2009-04-30 05:03:06

标签: python sql django stored-procedures django-models

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

7 个答案:

答案 0 :(得分:22)

我们(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]    
欢呼,西蒙。

答案 1 :(得分:16)

您必须在Django中使用连接实用程序:

from django.db import connection

cursor = connection.cursor()
cursor.execute("SQL STATEMENT CAN BE ANYTHING")

然后你可以获取数据:

cursor.fetchone()

或:

cursor.fetchall()

此处有更多信息:http://docs.djangoproject.com/en/dev/topics/db/sql/

答案 2 :(得分:4)

有一个很好的例子:  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()

答案 3 :(得分:2)

如果您想查看使用SP的实际运行项目,请查看minibooks。大量的自定义SQL并使用Postgres pl / pgsql for SP。我认为他们最终会删除SP(trac ticket 92中的理由)。

答案 4 :(得分:0)

别。

严重。

将存储过程逻辑移动到它所属的模型中。

在Django中放入一些代码,数据库中的一些代码是维护的噩梦。我花了30多年的时间在IT上试图清理这种混乱。

答案 5 :(得分:0)

我想Django 1.2中改进的原始sql查询集支持可以使这更容易,因为您不必滚动自己的make_instance类型代码。

答案 6 :(得分:0)

可以使用Cx_Oracle。另外,当我们无法访问生产部署的代码并且需要对数据库进行重大更改时,这将非常有帮助。

import cx_Oracle
try:
    db = dev_plng_con
    con = cx_Oracle.connect(db)
    cur = con.cursor()
    P_ERROR = str(error)
    cur.callproc('NAME_OF_PACKAGE.PROCEDURENAME', [P_ERROR])

except Exception as error:
    error_logger.error(message)