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