>>> 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
生のクエリセットの代わりにリストを渡すことで、この状況を回避できます。
>>> if list(Author.objects.raw("""select * from stack_author where id = 5""")):
... print 'yes'
...
>>>
スライスも機能します:
>>> if Author.objects.raw("""select * from stack_author where id = 5""")[:]:
... print 'yes'
...
>>>
ビューで qs を評価し、ブール値の結果をテンプレートに渡すこともできます。
空の raw qs で Indexing が IndexError を発生させることに注意してください。
>>> 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
何をしようとしているのかによっては、繰り返し処理を行う場合に for ループを使用することもできます。
>>> for author in Author.objects.raw("""select * from stack_author where id = 5"""):
... print author
...
>>>