2014-09-21 32 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