0

我正在使用 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使用他的别名访问数组。

4

1 回答 1

2

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

默认情况下,Python DB API 将返回不带字段名称的结果,这意味着您最终会得到一个值列表,而不是一个字典。以较小的性能成本,您可以使用以下内容将结果作为 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}]
于 2013-02-06T10:50:21.770 回答