我想对来自不同模型的两个不同属性应用算术运算,并获取json作为最终结果。例如在这种情况下,我想通过将price_per_km属性乘以第二个对象中的distance属性来计算每辆车的价格
此条目json
{
"cars": [
{ "id": 1, "price_per_day": 2000, "price_per_km": 10 },
{ "id": 2, "price_per_day": 3000, "price_per_km": 15 },
{ "id": 3, "price_per_day": 1700, "price_per_km": 8 }
],
"rentals": [
{ "id": 1, "car_id": 1, "start_date": "2017-12-8", "end_date": "2017-12-10", "distance": 100 },
{ "id": 2, "car_id": 1, "start_date": "2017-12-14", "end_date": "2017-12-18", "distance": 550 },
{ "id": 3, "car_id": 2, "start_date": "2017-12-8", "end_date": "2017-12-10", "distance": 150 }
]
}
预期的json *
{
"rentals": [
{
"id": 1,
"price": 7000
},
{
"id": 2,
"price": 15500
},
{
"id": 3,
"price": 11250
}
]
}
在哪里可以在viewset或serializer.py的queryset中编写sum方法? 如何自定义我的视图集以获取结果?