satyajit
satyajit

Reputation: 694

how to get minimum and maximum price from serializers?

To get minimum and maximum price from serializers i used inbuilt types of function(min, max). but it's throwing me error: 'int' object is not iterable.

views.py :

data = Product.objects.filter(status=1)
product_ser = FilterPriceSerializer(data,many=True)
filter_PriceData=[]
# print(product_ser.data)
for record in product_ser.data:
    value = json.dumps(record)
    temp = json.loads(value)

    price = temp['price']
    min_price = min(price)
    max_price = max(price)
    print(min_price)
    

    filter_PriceData.append({"price":price})

serializers.py :

class FilterPriceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = [
            "price"
        ]

Upvotes: 1

Views: 597

Answers (1)

Vishal Singh
Vishal Singh

Reputation: 6234

It looks like you don't need a for loop, you can directly use min, max on product_ser.data to calculate the maximum and minimum price.

data = Product.objects.filter(status=1)
product_ser = FilterPriceSerializer(data, many=True)

min_price = min(product_ser.data, key=lambda x: x["price"])
max_price = max(product_ser.data, key=lambda x: x["price"])

Upvotes: 1

Related Questions