Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with filtering data via custom function in Python (Django)

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 Products:

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading