Django 原始查询在 html 模板上没有 returning/rendering 结果

Django raw query not returning/rendering results on html template

我目前正在开发一个应用程序,我打算访问另一个应用程序的静态数据库。这两个应用程序是独立的,但共享同一个数据库。 由于我绕过了模型 class,我被要求在我的视图中执行一些原始 sql(准确地说是 postgrres)查询。 但是我的模板没有返回任何结果 这是视图和模板代码

#views code

def receipt(request):
cursor = connection.cursor()

# Data retrieval operation

    cursor.execute("SELECT * FROM quickpay_client_transactions")
    transactions = cursor.fetchall()

return render(request, 'receipt.html', {"transactions":transactions})


#Templates code snippet

{% for trans in transactions %}
                                            <tr>
                                                <td>
                                                {{trans.id}}    
                                                </td>
                                                <td></td>
                                                <td>{{trans.amount}}</td>
                                                  <th>{{trans.reference}}</th>
                                                <td>
                                                        <span class="label label-success">Success</span>
                                                </td>
                                                <th>{{trans.t_stamp}}</th>
                                            </tr>
                                            {% endfor %}

首先检查你在

中得到的任何结果
transactions = cursor.fetchall()

第二类交易应该是列表

带有虚拟数据的示例工作代码:

from django.shortcuts import render
def index(request):

    transactions = [{"id":1},{"id":2}]
    return render (request, 'test/index.html', {"transactions":transactions})

html:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
Test
{% for trans in transactions %}
                                            <tr>
                                                <td>
                                                {{trans.id}}
                                                </td>

                                            </tr>
                                            {% endfor %}
</body>
</html>

或者您的 sql 数据不在 str 中: 试试这个

transactions = [to_string(x) for x in cursor.fetchall()]
import datetime
import decimal
def to_string(x):
    a = []
    for y in x:
        if type(y) is datetime.datetime:
            a.append(str(y))
        elif type(y) is decimal.Decimal:
            a.append(str(y))
        elif type(y) is unicode:
            a.append(y.encode("UTF-8", "ignore"))
        elif type(y) is float:
            a.append(str(y))
        else:
            a.append(y)
    return a