2

当我对变量使用原始 sqlmyvar = some rawsql时,当我检查查询中的 if 条件时,myvar它始终为真。

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

例如,我的原始 sql 返回 0 条记录,然后我想显示一些消息,但我无法做到这一点。当我调试后台发生的事情时,我的原始 sql 总是返回一些对象 ( <RawQuerySet: "sel),即使 sql 获取空记录。所以这就是为什么 myvar 总是正确的,因为它持有一些原始查询集的对象。

有什么办法可以摆脱这种情况

提前致谢

4

1 回答 1

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

您可以通过传递列表而不是原始查询集来避免这种情况:

>>> 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
... 
>>> 
于 2011-05-20T06:01:28.240 回答