确定性地随机化查询集

时间:2013-09-14 19:48:58

标签: python django

我在Django中有一个查询集:

Books.objects.filter(name=variable)

我想在我的用户中随机显示此列表(两个不同的用户不会以相同的顺序看到这些书)。但是如果他多次回来,我希望同一个用户的订单保持不变。

有没有一种方法,给定一个特定于我的用户的整数(比如说他的user.id),随机化查询集?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您可以创建单独的random.Random对象:

from random import Random

r = Random()
r.seed(some_user_id)
books = Books.objects.filter(name=variable)
jumbled = sorted(books, key=lambda L: r.random())

答案 1 :(得分:0)

您可以在数据库中随机化它:

Books.objects.filter(name=variable).order_by('?')

但最好将列表存储在缓存中,然后随机化缓存列表。

出于开发目的,您可以在settings.py

中使用虚拟缓存
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

在制作中,您应该使用supported cache

设置完成后,在您的用户登陆的第一个视图的视图中,从数据库中获取项目并将其存储在缓存中:

import random

from django.core.cache import cache

@login_required
def index(request):
   cache_key = '{0}-books'.format(request.user.pk)
   book_list = cache.get(cache_key)
   if not book_list:
      # There was nothing in the cache, so we fetch the items
      # and add them in the cache

      # Here we set it to expire after 3600 seconds (1 hour)
      book_list = list(Book.objects.filter(name=variable))
      random.shuffle(book_list)
      cache.set(cache_key, book_list, 3600)


   # the rest of your code