>>> 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 并将布尔结果传递给模板。
小心 Indexing 会在空的原始 qs 上引发 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
...
>>>