Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Get 10 random instances from a queryset and order them into a new queryset?

Tags:

python

django

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?

like image 262
EazyC Avatar asked Sep 04 '15 03:09

EazyC


1 Answers

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)

Hope it helps, also please go through django queryset docs

like image 147
Saurabh Goyal Avatar answered Sep 20 '22 01:09

Saurabh Goyal