0

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'.
1
  • Try printing collection probably, what exactly you getting there Commented Apr 22, 2021 at 23:53

1 Answer 1

3

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 :) )

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! And that's an awesome tool! I'll be using that alot!
I'd be glad if you could leave a like to repo of this app :) github.com/titans55/json-to-drf-serializers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.