[Django]-How to access extra data sent with POST request in Django Rest Framework serializer

3👍

To send extra context data you should pass it from the method def get_serializer_context(self) and access inside serializer like self.context.get("key").

sample code:

class GroupListView(ListCreateAPIView):
    queryset = Group.objects.all()

    def get_serializer_context(self):
        context = super(GroupListView, self).get_serializer_context()
        context["users_to_invite"] = request.data.get("users_to_invite")
        return context

class GroupCreateSerializer(ModelSerializer):

    def create(self, validated_data):
        users_to_invite = self.context.get("users_to_invite")
        # do whatever you want

6👍

extra data is absent in validated_data you can try use self.context['request'] details: including-extra-context, by default it added in the get_serializer method of view

for your case:

def create(self, validated_data):
    # Get user ids to invite
    # !! It fails here !!
    request = self.context['request']
    invitations_data = request.data.get('users_to_invite')

0👍

Apart from adding the data to context, you can add the field users_to_invite to serializer as a CharField.

Example:

import json

class GroupCreateSerializer(ModelSerializer):

    def create(self, validated_data):
        # Get user ids to invite
        # !! It fails here !!
        invitations_data = json.loads(validated_data.pop('users_to_invite'))

        # TODO: Iterate over ids and create invitations

        # Create a group
        group = Group.objects.create(**validated_data)
        return group

    users_to_invite = serializers.CharField(required=False)

    class Meta:
        model = Group
        fields = ('id', 'name', 'users_to_invite', )

Note: Make sure to have users_to_invite in request data as a string. Like: '[1, 2, 3]'

👤Sachin

Leave a comment