Django Rest Framework serializers beautiful output

Viewed 32

I have model of category and need to serialize to give beautiful output.

My model

class Categorie(models.Model):
    name = models.CharField(max_length=50)

My serializer

class CategorieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Categorie
        fields = ['name']

My code

class JokesCategories(APIView):

    def get(self, request):
        categories = Categorie.objects.all()
        serializer = CategorieSerializer(categories, many=True)
        output_data = {}
        for num, dictionary in enumerate(serializer.data):
            output_data[num] = dict(dictionary)['name']
        return Response(output_data)

I have output

{
    "0": "animal",
    "1": "career"
}

But need

[
    0: "animal",
    1: "career"
]

Help for you advices.

1 Answers

You can't. A JSON object always has strings as keys, not integers. This is part of the JSON specifications [json.org]. You can for example use jsonlint to check if a certain text is valid JSON, and the latter is not.

Python's JSON encoder thus will fallback on converting the integers into strings to produce a valid JSON blob. Your dictionary indeed produced integers as keys, but the serializer thus converts it to strings.

Here it however might make more sense to use a list, and not an object, since the keys (indices) start at 0 and are incremental. Using a dictionary/JSON object thus does not make much sense:

class JokesCategories(APIView):

    def get(self, request):
        categories = Categorie.objects.all()
        serializer = CategorieSerializer(categories, many=True)
        output_data = [data['name'] for item in serializer.data]
        return Response(output_data)
Related