使用Django执行原始SQL查询

Ess*_*sex -1 python mysql django django-queryset

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

例如 :

用户想要搜索我桌上名为'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))
Run Code Online (Sandbox Code Playgroud)

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

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

{% block content %}

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

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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

我读了一些教程:Django Raw SQL Query但暂时没有结果.

非常感谢 !

Sha*_*nis 5

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

from django.shortcuts import render
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

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

{% block content %}

{{ row }}

{% endblock %}
Run Code Online (Sandbox Code Playgroud)