2

変数に生のSQLを使用しているとき、およびクエリの条件が常に真myvar = some rawsqlであるかどうかをチェックインしているとき。myvar

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

たとえば、生のSQLが0レコードを返し、メッセージを表示したいのですが、それができませんでした。バックグラウンドで何が起こっているかをデバッグすると、SQL が<RawQuerySet: "sel空のレコードをフェッチしても、生の SQL は常に何らかのオブジェクト ( ) を返します。そのため、生のクエリセットのオブジェクトを保持しているため、myvar は常に true です。

この状況から抜け出す方法はありますか

前もって感謝します

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 を評価し、ブール値の結果をテンプレートに渡すこともできます。


空の 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
... 
>>> 
于 2011-05-20T06:01:28.240 に答える