使用 Django 执行原始 SQL 查询

Performing Raw SQL Queries with Django

我正在寻找用 Django 创建一些 SQL queries 但我没有显示结果。 这个查询非常重要,因为我想配置一个客户端使用的研究栏。

例如:

一位用户想要搜索我的 table 中名为 'Dupont' 且居住在纽约

的所有人

在我的 views.py 中,我写了类似的东西 :

def Test(request) :

    cursor = connection.cursor()
    cursor.execute('''SELECT * FROM BirthCertificate_people WHERE `name` = "Dupont" AND `city` = "New-York"''')
    row = cursor.fetchone()

    print row

    template = loader.get_template('test.html') 
    return HttpResponse(template.render(request))

在我的模板文件中 test.html :

<h2 align="center"> SQL Queries display </align> </h2>

{% block content %}

<!-- What I write there --> {{ }}

{% endblock %}

我不知道如何在我的 .html 文件中显示 SQL 查询结果。

我读了一些教程:Django Raw SQL Query 但 none 目前的结果..

非常感谢!

您需要将行作为上下文传递,以便可以在 html 中访问它。一种方法是通过 1) 在你的 views.py 中导入 render

from django.shortcuts import render

2) 现在一起传递模板和上下文

def Test(request) :

    cursor = connection.cursor()
    cursor.execute('''SELECT * FROM BirthCertificate_people WHERE `name` = "Dupont" AND `city` = "New-York"''')
    row = cursor.fetchone()

    print row

    context = {"row":row}
    return render(request, "test.html", context)

3) 现在在您的模板中 "test.html" 您可以访问您的行:-

<h2 align="center"> SQL Queries display </align> </h2>

{% block content %}

{{ row }}

{% endblock %}