以下是django中的示例代碼。Django:隨機排序(order_by('?'))使附加查詢
[案例1]
views.py
from sampleapp.models import SampleModel
from django.core.cache import cache
def get_filtered_data():
result = cache.get("result")
# make cache if result not exists
if not result:
result = SampleModel.objects.filter(field_A="foo")
cache.set("result", result)
return render_to_response('template.html', locals(), context_instance=RequestContext(request))
template.html
{% for case in result %}
<p>{{ case.field_A}}</p>
{% endfor %}
在這種情況下,有沒有產生的高速緩存作出後查詢。我檢查了django_debug_toolbar。
[情況2]
views.py - 增加一個線result = result.order_by('?')
from sampleapp.models import SampleModel
from django.core.cache import cache
def get_filtered_data():
result = cache.get("result")
# make cache if result not exists
if not result:
result = SampleModel.objects.filter(field_A="foo")
cache.set("result", result)
result = result.order_by('?')
return render_to_response('template.html', locals(), context_instance=RequestContext(request))
template.html - 相同前一個
在這種情況下,它生成新的查詢即使我緩存過濾查詢。
我該如何適應無附加查詢集的隨機排序?
製作緩存時我不能放
order_by('?')
。 (例如result = SampleModel.objects.filter(field_A="foo").order_by('?')
) 因爲它甚至會緩存隨機順序。它與' django queryset是懶惰'?
在此先感謝。
哇,你提出的解決方案真的很棒。謝謝! – 2014-09-22 00:58:41