【问题标题】:issues with raw MySQL queries in djangodjango 中原始 MySQL 查询的问题
【发布时间】:2013-02-06 08:48:46
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: python mysql django django-queryset


    【解决方案1】:

    从这里: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}]
    

    【讨论】:

    • 谢谢。我在看这个
    猜你喜欢
    • 2022-06-16
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2013-04-17
    • 1970-01-01
    • 2015-11-21
    • 2012-03-16
    相关资源
    最近更新 更多