2014-09-21 43 views
2

以下是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是懶惰'?

在此先感謝。

回答

6

.order_by在數據庫級執行排序。

這裏是一個例子。我們將lasy查詢集存儲在var results中。沒有查詢尚未作出:

results = SampleModel.objects.filter(field_A="foo") 

觸摸results,例如,通過遍歷它:

for r in results: # here query was send to database 
    # ... 

現在,如果我們再這樣做,沒有試圖將數據庫製作,因爲我們已經有了這個確切的查詢:

for r in results: # no query send to database 
    # ... 

但是,當你申請.order_by,查詢會有所不同。所以,Django的必須發送新的請求給數據庫:

for r in results.order_by('?'): # new query was send to database 
    # ... 

解決方案

當你在Django查詢,你知道,你會得到所有的元素從該查詢(即無OFFSET和LIMIT),那麼你可以在你從數據庫中獲取它們之後,用python處理這些元素。

results = list(SampleModel.objects.filter(field_A="foo")) # convert here queryset to list 

在該行的查詢作出,你必須在results所有元素。

如果你需要得到隨機的順序,做到在蟒蛇現在:

from random import shuffle 
shuffle(results) 

之後,結果將有隨機的順序,無需額外的查詢被髮送到數據庫中。

+0

哇,你提出的解決方案真的很棒。謝謝! – 2014-09-22 00:58:41