JeremyE
JeremyE

Reputation: 1418

Django Rest Framework - Creating nested JSON without a Model

I'm looking for an output similar to:

 "live_collection": {
      "buy": 420,
      "sell": 69,
 },

I'm not using a model. Instead, I'm aggregating data from a different model. That part is working fine as I'm able to create a flat JSON response - but I attempt to nest it like the above, I run into issues.

Here is the 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)

The serializer.py

class PlayerCollectionLiveSerializer(serializers.Serializer):
    live_collection__buy = serializers.IntegerField()
    live_collection__sell = serializers.IntegerField()

And here is the error I'm getting:

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'.

Upvotes: 0

Views: 852

Answers (1)

KutayAslan
KutayAslan

Reputation: 494

You could serialize the mentioned json using the serializers below:

from rest_framework import serializers

class LiveCollectionSerializer(serializers.Serializer):
    buy = serializers.IntegerField()
    sell = serializers.IntegerField()

class RootSerializer(serializers.Serializer):
    live_collection = LiveCollectionSerializer()

Note: I have generated those serializers using an app that I created for this purpose. You can play around and figure out how serializers works in drf. https://titans55.github.io/json-to-drf-serializers/ (Just paste the json you want to serialize into Input in the left and click generate :) )

Upvotes: 3

Related Questions