Riko
Riko

Reputation: 131

Custom JSON callback using Django Rest Framework

I'm just trying to write a mobile app using https://jasonette.com/, but it wants backend specific JSON format for an each response, something like below:

{
  "$jason": {
    "head": {
      "title": "{ ˃̵̑ᴥ˂̵̑}",
      "actions": {
        "$foreground": {
          "type": "$reload"
        },
        "$pull": {
          "type": "$reload"
        }
      }
    },
    "body": {
      "header": {
        "style": {
          "background": "#ffffff"
        }

For test purposes I serialised regular django_user model:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email')

And it returns a JSON-object with a user list. But how I can customize this JSON with additional values and format it as a Jasonette wants?

Upvotes: 1

Views: 974

Answers (2)

Igonato
Igonato

Reputation: 10787

You can change serialization behavior by overriding .to_representation() method in your serializer:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email')

    def to_representation(self, user):
        data = super().to_representation(user)  # the original data

        return {
            '$jason': {
                'head': {
                    # ...
                },
                'body': data,
                # ...
            }
        }

Upvotes: 2

gurch101
gurch101

Reputation: 2064

The serializer will handle conversion of the object instance to a dictionary of primitive datatypes and vice-versa (just like a django Form). If you want to augment the JSON response, override the corresponding view method. As an example, you can do something like the following in your view:

from rest_framework.response import Response


class UserViewSet(ModelViewSet):
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        data.update({"foo": "bar"})
        return Response(data)

Upvotes: 3

Related Questions