user984003
user984003

Reputation: 29589

Django: Access raw sql results directly in template without looping - since only returns one row

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

Answers (1)

cetver
cetver

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

Related Questions