我正在为我的api开发一个带有Django后端和DRF框架的应用程序。
在给定的url中,我想显示每个用户的索引(排名),一旦列表在我的视图上排序。我不能很好地解释它,所以我在我的信息的最后加了两个例子。
我没有在互联网上找到任何关于如何在不修改模板添加字段的情况下做到这一点(我不能使用这个解决方案)。
你有主意吗?
谢谢!
Below my view:
class RankBestPurchaserViewset(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = RankUserAllPurchaseSerializer(queryset, many=True)
sortedList = sorted(serializer.data, key=itemgetter(
'amount'), reverse=True)
return Response(sortedList)
在序列化器下面:
class RankUserAllPurchaseSerializer(serializers.BaseSerializer):
def to_representation(self, instance):
return {
'id': instance.id,
'username': instance.username,
'surname': instance.surname,
'amount': float(SaleProduct.objects.filter(sale__sender__username=instance.username).aggregate(Sum('price'))['price__sum'] or 0),
'qty_amount': SaleProduct.objects.filter(sale__sender__username=instance.username).count(),
}
结果下面:
[
{
"id": 3,
"username": "An20",
"surname": "Khalvin",
"amount": 426.7,
"qty_amount": 110
},
{
"id": 1,
"username": "AA_ENS",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
},
{
"id": 4,
"username": "in22",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
}
]
想要的结果
[
{
"index":1,
"id": 3,
"username": "An20",
"surname": "Khalvin",
"amount": 426.7,
"qty_amount": 110
},
{
"index":2,
"id": 1,
"username": "AA_ENS",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
},
{
"index":3
"id": 4,
"username": "in22",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
}
]
or
[
1:{
"id": 3,
"username": "An20",
"surname": "Khalvin",
"amount": 426.7,
"qty_amount": 110
},
2:{
"id": 1,
"username": "AA_ENS",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
},
3:{
"id": 4,
"username": "in22",
"surname": "gum",
"amount": 0.0,
"qty_amount": 0
}
]
也许你可以在视图中添加代码。
class RankBestPurchaserViewset(viewsets.ViewSet):
def list(self, request):
...
sortedList = sorted(serializer.data, key=itemgetter(
'amount'), reverse=True)
# here I added the code to add the ranking index
for index, sortedItem in enumerate(sortedList):
sortedList[index].update('index', index + 1)
return Response(sortedList)
感谢@David Lu这就是答案:
class RankBestPurchaserViewset(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = RankUserAllPurchaseSerializer(queryset, many=True)
sortedList = sorted(serializer.data, key=itemgetter(
'amount'), reverse=True)
for index, sortedItem in enumerate(sortedList):
sortedList[index].update(index=index+1)
return Response(sortedList)