Django:从一个查询集中获取10个随机实例,然后将它们排序到一个新的查询集中? [英] Django: Get 10 random instances from a queryset and order them into a new queryset?
问题描述
我想为我的应用程序创建一个动态主页,每次访问该主页时,该网站都会使用该网站的10个不同页面/个人资料.我知道用于随机查询的django SQL查询非常慢,因此我试图通过创建一个空列表,创建一个随机数列表,然后抓取第n个随机元素来编写自己的(伪)随机样本方法查询集并将其放入列表中.
I want to create a dynamic homepage for my app that features 10 different pages/profiles of people using the site each time the home page is accessed. I know that the django SQL query for randomized query is extremely slow so I am trying to write my own method of doing this (pseudo)random sample by creating an empty list, and creating a list of random numbers and then grabbing the random nth element of the queryset and placing that into the list.
import random
profilelist = [] #create an empty list
qindex = ProfilePage.objects.filter(profileisbannedis=False) #queryset for all of possible profiles to be displayed
randlist = random.sample(xrange(qindex.count()), 10) #create a list of 10 numbers between range 0 and the size of the queryset.
#this method also does not repeat the same randomly generated number which is ideal since I don't want to feature the same profile twice
for i in randlist:
tile = qindex[i] #for each random number created, get that element of the queryset
profilelist.extend(tile) #place each object in the previous queryset into a new list of objects and continue extending the list for each of 10 random numbers
我真的不知道该怎么做,因为我知道在代码的最后一行出现错误对象不可迭代",因此像这样逐段创建一个新的查询集是不合适的办法.我该如何做/从以前的过滤查询集中创建我的随机查询集?
I can't really figure out how to do it this way since I know I get the error "object is not iterable" on the last line of the code so creating a new queryset piece by piece like this is not the proper way. How can I go about doing this/creating my random queryset made from a previous filtered queryset?
推荐答案
您可以做的一件事是获取查询集中随机元素的ID列表(假设"id"是主键),然后进行过滤那些.类似于以下代码:
One thing you can do is take a list of ids (assuming, 'id' is the primary key) of random elements in the queryset, and then filter on those. Something like the code below:
import random
valid_profiles_id_list = ProfilePage.objects.filter(profileisbannedis=False).values_list('id', flat=True)
random_profiles_id_list = random.sample(valid_profiles_id_list, min(len(valid_profiles_id_list), 10))
query_set = ProfilePage.objects.filter(id__in=random_profiles_id_list)
希望它会有所帮助,也请仔细阅读 django queryset文档
Hope it helps, also please go through django queryset docs
这篇关于Django:从一个查询集中获取10个随机实例,然后将它们排序到一个新的查询集中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!