【问题标题】:Django: format raw query for template when using cursor.execute()Django:使用 cursor.execute() 时为模板格式化原始查询
【发布时间】:2013-01-10 18:10:21
【问题描述】:

我需要执行原始查询:

 cursor.execute("select id, name from people")
 results = cursor.fetchall()

如何转换它以便在 Django 模板中使用它:

{% for person in results %}
  {{person.name}}
{% endfor %}

通常,我会使用模型:

results = people.objects.raw("select id, name from people")

无论我在查询中使用多少其他模型/表,它都有效。

但是,该方法要求我包含人员模型的主 ID。这次我不能这样做,因为 sql 实际上是一个 group by 查询,并且不能包含 id。

我绝对想使用原始 sql,而不是其他类似“group by”的方式。

【问题讨论】:

  • 您想要执行的实际查询是什么?也许可以通过 django ORM 来做到这一点。

标签: python django django-templates


【解决方案1】:

这行得通。将元组的元组转换为字典列表,并从 cursor.description 中获取字段描述。可以做成一个小功能。并且可能有一些聪明的 lamdba 东西可以让它更短。

        cursor = connection.cursor()
        cursor.execute(my_select)
        results = cursor.fetchall()

        x = cursor.description
        resultsList = []   
        for r in results:
            i = 0
            d = {}
            while i < len(x):
                d[x[i][0]] = r[i]
                i = i+1
            resultsList.append(d)

        return render_to_response(my_template, {"results":resultsList})

【讨论】:

    【解决方案2】:

    如果您坚持需要使用 MySQLdb 游标执行原始 sql 查询,则创建一个字典游标DictCursor,以便可以按名称而不是按位置访问列值。

     cursor.close ()
     cursor = conn.cursor (MySQLdb.cursors.DictCursor)
     cursor.execute ("SELECT id, name FROM people")
     results = cursor.fetchall ()
     for row in results:
         print "%s, %s" % (row["id"], row["name"])
    

    使用DictCursor,您不需要做任何事情,只需将它传递给模板并像使用 django 查询集一样使用它。

    【讨论】:

    • 这不起作用。似乎您必须在 connect() 中提供 MySQLdb.cursors.DictCursor 参数,而不是 cursor()。但我正在使用 Django 自动进行连接。顺便说一句,这需要导入 MySQLdb
    • 这是为 MySQLdb 游标而不是 django db 游标。
    • 但是我必须做连接提供密码等?我喜欢 Django 为我这样做。
    猜你喜欢
    • 2020-05-24
    • 2012-07-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多