如何从序列化器获得最低和最高价格?

时间:2020-07-25 06:44:36

标签: python django-rest-framework

为了从串行器中获得minimummaximum的价格,我使用了内置的函数类型(最小值,最大值)。但这会抛出错误:'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"
        ]

1 个答案:

答案 0 :(得分:1)

似乎不需要for循环,您可以直接在product_ser.data上使用min,max来计算最高和最低价格。

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