有没有一种方法可以改组查询集,使其每天显示不同的值?

时间:2019-01-30 16:06:13

标签: django django-queryset shuffle

我正在构建一个Django 2.5 Web应用程序,该应用程序每天都显示与历史人物不同的报价。问题在于,每个用户的报价都应该不同,并且每天都要更改,而不必重复相同的报价。

我已经做过一些研究,唯一接近的是我请求查询集时使用了偏移量,但这不能解决每个用户问题的随机引用。

quotes/views.py
import datetime

...

now = datetime.datetime.now()
today_tt = now.timetuple()
julian_day = today_tt.tm_yday
#asuming there are 365 quotes on the database
quotes.objects.all()[jualian_day]

我该怎么做?

1 个答案:

答案 0 :(得分:0)

import random

# TODO Retrieve into pks_used the previously saved primary keys 
# of the quotes already displayed to the current user
pks_used = set()

# Get the primary keys of all quotes
all_pks = set(quotes.objects.values_list('pk', flat=True))

# Exclude the quotes that have been shown already
eligible_pks = all_pks - pks_used

# Get a random quote from the list of unused quotes
# random.sample returns a list 
# (with just one element in our case)
rnd_pk = random.sample(eligible_pks, 1)[0]
todays_quote = quotes.objects.get(pk=rnd_pk)

# TODO display the quote and store its private key in the list of 
# already displayed quotes