How to pass raw sql results (cursor.fetchall()) to the template?

1,722 views
Skip to first unread message

Ken

unread,
Jan 14, 2010, 5:01:18 PM1/14/10
to Django users
Newb question here. How do I pass raw sql results to my template?
The sql results contains a two column queryset with several rows .

Below doesn't work. How do I make this work? Do I need to parse the
results into an array and then pass to the template?

IN THE VIEW:
cursor = connection.cursor()
cursor.execute("query goes here")
results = cursor.fetchall()

return render_to_response('template.html', {'results': results})

IN THE TEMPLATE:
{% for result in results %}
<br>{{ result[0] }} is a big {{ result[1] }}
{% endfor %}


Tomasz Zieliński

unread,
Jan 15, 2010, 7:38:48 AM1/15/10
to Django users

I haven't checked this in shell, but it looks to be correct,
except that you should write: {{ result.0 }} instead of {{ result
[0] }}

Here's the relevant doc section:

http://docs.djangoproject.com/en/1.1/topics/templates/#variables

--
Tomasz Zielinski
http://pyconsultant.eu

Reply all
Reply to author
Forward
0 new messages