Andromedae93 Andromedae93 - 9 days ago 5
Python Question

Performing Raw SQL Queries with Django

I'm looking for create some

SQL queries
with Django but I don't have a display result.
This queries are very important because I would like to configure a research bar used by client.

For example :

A user wants to search all people in my table which are named 'Dupont' and living in New-York

In my
views.py
, I have written something like that :

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))


In my template file
test.html
:

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

{% block content %}

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

{% endblock %}


I don't know How I can display the SQL queries results in my .html file.

I read some tutorials : Django Raw SQL Query but none results for the moment ..

Thank you so much !

Answer

You need to pass the row as a context so that it can be accessed in the html. One way to do this is by 1) Inside your views.py import render

from django.shortcuts import render

2) Now pass the template and context together

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) Now inside your template "test.html" you can access your row:-

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

{% block content %}

{{ row }}

{% endblock %}
Comments