[Answered ]-Problem with filtering data via custom function in Python (Django)

1👍

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))

Leave a comment