Home > Enterprise >  Use data as Django response field name?
Use data as Django response field name?

Time:07-06

I have the following data class:

class IndustryScore:
    industry: str
    score: Decimal

class Foo:
    ...
    industry_scores = List[IndustryScore]

I want the response to be something where the key of the response is the industry and the score is the value. For example:

{
    "automotive": 5.1,
    "construction": 10.0,
    "technology": 8.6,
}

Right now I have a serializer like this:

class IndustryScoreSerializer(serializers.Serializer):
    industry = serializers.Charfield()
    score = serializers.DecimalField()

but the response is something like this instead:

[
    {
        industry: "automotive",
        score: 5.1
    }
]

How can I change the serializer so I get the expected JSON structure?

CodePudding user response:

The response is right, it's in an array so that you can loop over it, so everything works fine,

but if you insist, you can make the response as your example, just don't use a serializer,and create a dictionary and append the values to it, which will make an errors in your frontend because the keys are changing.

CodePudding user response:

Posting my own answer here since I figured out an alternative method. Using the serializers.SerializerMethodField you can do the following without having to create a IndustryScoreSerializer:

class FooSerializer:
    industry_scores = serializers.SerializerMethodField()

    def get_industry_scores(self, data):
        return {score.industry: score.score for score in data.industry_scores}
  • Related