2

When I am using raw sql for a variable say myvar = some rawsql and when I am checking in if condition in query for myvar it is always true.

{% if myvar %}
 do this;
{% else %}
 do this;
{% endif %}

For instance my raw sql returns 0 records then I want to display some message, but I could not able to do that. When I debugged whats happening in the background, my raw sql always returns some object (<RawQuerySet: "sel) eventhough sql fetches empty records. So thats why myvar is always true because its holding some object of raw queryset.

Is there any way to getrid of this situation

Thanks in advance

vkrams
  • 7,267
  • 17
  • 79
  • 129

1 Answers1

1
>>> Author.objects.raw("""select * from stack_author where id = 5""")
<RawQuerySet: 'select * from stack_author where id = 5'>
>>> list(_)
[]
>>> 
>>> if Author.objects.raw("""select * from stack_author where id = 5"""):
...     print 'yes'
... 
yes

You can avoid this situation by passing a list instead of a raw queryset:

>>> if list(Author.objects.raw("""select * from stack_author where id = 5""")):
...     print 'yes'
... 
>>> 

Slicing would also work:

>>> if Author.objects.raw("""select * from stack_author where id = 5""")[:]:
...     print 'yes'
... 
>>> 

You could also evaluate the qs in the view and pass a boolean result to the template.


Careful that Indexing will raise an IndexError on an empty raw qs:

>>> if Author.objects.raw("""select * from stack_author where id = 5""")[0]:
...     print 'yes'
... 
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/dennisting/.virtualenvs/django-sb/lib/python2.7/site-packages/django/db/models/query.py", line 1379, in __getitem__
    return list(self)[k]
IndexError: list index out of range

Using a for loop if you are iterating works as well depending on what you are trying to do:

>>> for author in Author.objects.raw("""select * from stack_author where id = 5"""):
...     print author
... 
>>> 
dting
  • 38,604
  • 10
  • 95
  • 114
  • Awsome :-) thanks a ton. I made it work like this. I am making raw query variable as condition = list(myvar) and in the template I am making {% if condition %} do this; {% else %} do this; {% endif %} – vkrams May 20 '11 at 06:19