I want to get 4 random objects from Product
I'm trying to filter it by check_existing_id
function and random.randint
and I use while
loop to get 4 objects from the database. However this piece of code in some cases returns only 3 objects. There is a bug hidden in the code and I have no idea where I need this to return exacly 4 elements every single time. I'm pasting the code below it's just a simple function:
def check_existing_id(list,number):
for i in range(len(list)):
if list[i] == number:
return False
return True
class GetRecommendedProducts(generics.ListAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
product_id = self.kwargs['product_id']
products_length = len(Product.objects.all())
id_list = []
while len(id_list) < 4:
id = random.randint(0, products_length)
if check_existing_id(id_list, id) and id != product_id:
id_list.append(id)
return Product.objects.filter(id__in=id_list)
CodePudding user response:
You can make use of the sample(…)
function [Python-doc] of the random
package [Python-doc]. You can first fetch the list of primary keys (excluding the product_id
), then sampling four items, and then fetch the Product
s:
from random import sample
class GetRecommendedProducts(generics.ListAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
id_list = list(Product.objects.exclude(
id=self.kwargs['product_id']
).values_list('id', flat=True))
return Product.objects.filter(id__in=sample(id_list, 4))