Reputation: 29589
I return the following:
return render_to_response('mypage.html', { "results":results})
In my view function, I can get results either like this:
results = listings.objects.get(id = 1)
In which case I can use it directly in the template:
{{results.name}}
or, I can get results like this (raw sql):
results = listings.objects.raw(sql_query, [id,])
Then I have to loop through it, even though I know it only returns 1 row:
{% for listing in results %}
{{listing.name}}
What I need is to be able to use the raw sql, but still not have to loop through it. The issue with looping is that, if results is empty, then nothing inside the loop gets displayed.
Upvotes: 0
Views: 1222
Reputation: 11829
results = listings.objects.raw(sql_query, [id,])[0]
or custom method:
def get_results():
from django.db import connection
cursor = connection.cursor()
cursor.execute(sql)
return cursor.fetchone()
Upvotes: 1