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

标签 python sql django stored-procedures django-models

我正在设计一个相当复杂的数据库,并且知道我的一些查询将远远超出 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/

相关文章:

python - 可以使用 Python 3 的数字格式将数字四舍五入到百、千等

Python/Django 模型

python - 如何向 dexml 中的标签添加属性?

php - SQL 好友列表创建

python - 在 Django Shell 中更改模型字段

python - 并行调用对象方法

php - 有没有办法在sql查询中返回多个不相关的结果?

mysql - SQL从表中删除查询

python - 每次编辑对象时,DateField 都会自行清除

mysql - 在 django 中建模以存储员工特定年、月和周的工作时间