django中的原始MySQL查询问题

时间:2013-02-06 08:48:46

标签: python mysql django django-queryset

我使用Django原始sql查询使用连接和别名来从数据库中获取数据 我的查询:

SELECT DISTINCT
   A.entity_id AS entity_id,
   A.email AS email,
   A.catquizid AS style_quiz_score,
   A.catquizquesans AS style_quiz_answer,
   A.created_at AS date_joined,
   A.is_active AS is_active,
   B.attribute_id AS attribute_id,
   B.value AS info
FROM
   customer_entity AS A INNER JOIN customer_entity_varchar AS B
   ON A.entity_id=B.entity_id WHERE B.attribute_id LIMIT 2

我正在取这样的结果:

row = cursor.fetchall()

当我返回HttpResponse行时,它会显示正确的结果,但如果我返回HttpResponse(row['entity_id']),则会显示错误Sorry, an error occurred.

所以请告诉我如何使用他的别名来访问数组row

1 个答案:

答案 0 :(得分:2)

从这里开始:https://docs.djangoproject.com/en/dev/topics/db/sql/

默认情况下,Python DB API将返回没有字段名称的结果,这意味着您最终得到的是值列表,而不是dict。以较低的性能成本,您可以使用以下内容将结果作为dict返回:

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");
>>> cursor.fetchall()
((54360982L, None), (54360880L, None))

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