在django中使用dict_cursor [英] Using dict_cursor in django

查看:260
本文介绍了在django中使用dict_cursor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在django中获取光标,请执行以下操作:

 从django.db导入连接
cursor = connection。 cursor()

如何在django中获取一个dict游标,相当于 -

  import MySQLdb 
connection =(建立连接)
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)

有没有办法在django中执行此操作?当我尝试 cursor = connection.cursor(MySQLdb.cursors.DictCursor)我得到一个异常值:cursor()只需要1个参数(2个给定)。或者我需要直接连接python-mysql驱动程序?



django文档建议使用 dictfetchall :< $ p

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ cursor.description
return [
dict(zip([col [0] for col in desc],row))
for cursor.fetchall()
]

使用这个和创建一个dict_cursor之间是否存在性能差异?

解决方案

在django中没有对 DictCursor 的支持。但是您可以为您编写一个小功能,请参阅此门票



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
dict(zip([col [0] for col in desc],row))
for cursor.fetchall()
]

>> ;> cursor.execute(SELECT id,parent_id from test LIMIT 2);
>>> dictfetchall(cursor)
[{'parent_id':None,'id':54360982L},{'parent_id':None,'id':54360880L}]
pre>

To get a cursor in django I do:

from django.db import connection
cursor = connection.cursor()

How would I get a dict cursor in django, the equivalent of -

import MySQLdb
connection = (establish connection)
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)

Is there a way to do this in django? When I tried cursor = connection.cursor(MySQLdb.cursors.DictCursor) I got a Exception Value: cursor() takes exactly 1 argument (2 given). Or do I need to connect directly with the python-mysql driver?

The django docs suggest using dictfetchall:

def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]

Is there a performance difference between using this and creating a dict_cursor?

解决方案

No there is no such support for DictCursor in django. But you can write a small function to that for you, see this ticket:

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [
            dict(zip([col[0] for col in desc], row)) 
            for row in cursor.fetchall() 
    ]

>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
>>> dictfetchall(cursor)
[{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}] 

这篇关于在django中使用dict_cursor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆