Python Django Rest框架-创建无模型的嵌套JSON
我正在寻找类似以下内容的输出:Python Django Rest框架-创建无模型的嵌套JSON,python,django,django-rest-framework,Python,Django,Django Rest Framework,我正在寻找类似以下内容的输出: "live_collection": { "buy": 420, "sell": 69, }, 我用的不是模型。相反,我正在聚合来自不同模型的数据。这部分工作正常,因为我能够创建一个简单的JSON响应——但我试图像上面那样嵌套它,我遇到了一些问题 以下是view.py: class PlayerCollectionLiveView(APIView): def get(
"live_collection": {
"buy": 420,
"sell": 69,
},
我用的不是模型。相反,我正在聚合来自不同模型的数据。这部分工作正常,因为我能够创建一个简单的JSON响应——但我试图像上面那样嵌套它,我遇到了一些问题
以下是view.py:
class PlayerCollectionLiveView(APIView):
def get(self, request):
live_collection_buy = list(PlayerProfile.objects.filter(series="Live").aggregate(Sum('playerlisting__best_buy_price')).values())[0]
live_collection_sell = list(PlayerProfile.objects.filter(series="Live").aggregate(Sum('playerlisting__best_sell_price')).values())[0]
collections = {
"live_collection": {
"buy": live_collection_buy,
"sell": live_collection_sell,
},
}
results = PlayerCollectionLiveSerializer(collections, many=True).data
return Response(results)
serializer.py
class PlayerCollectionLiveSerializer(serializers.Serializer):
live_collection__buy = serializers.IntegerField()
live_collection__sell = serializers.IntegerField()
下面是我得到的错误:
Got AttributeError when attempting to get a value for field `live_collection__buy` on serializer `PlayerCollectionLiveSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `str` instance.
Original exception text was: 'str' object has no attribute 'live_collection__buy'.
您可以使用以下序列化程序序列化提到的json:
from rest_framework import serializers
class LiveCollectionSerializer(serializers.Serializer):
buy = serializers.IntegerField()
sell = serializers.IntegerField()
class RootSerializer(serializers.Serializer):
live_collection = LiveCollectionSerializer()
注意:我已经使用为此目的创建的应用程序生成了这些序列化程序。您可以尝试并了解序列化程序在drf中的工作方式。
(只需将要序列化的json粘贴到左侧的输入中,然后单击generate:)尝试打印集合,可能会得到什么,谢谢!这是一个很棒的工具!我会用很多的!如果您能留下一个类似于此应用程序的repo,我将非常高兴:)