Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.8 getting kwargs in Serializer

This seems a bit odd to me, but works for now. Since I am very new in django/python, tell me how you would solve the problem. Goal is to create a Waypoint Object, which has a Trip id as parameter in the path. Trip is foreignkey for Waypoint.

class WaypointSerializer(serializers.ModelSerializer):
    trip = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Waypoint
        fields = ('id', 'trip', 'position', 'time')

    def create(self, validated_data):
        trip_id = self.context.get('request').parser_context['kwargs']['pk']
        validated_data['trip'] = Trip.objects.get(pk=trip_id)
        return super(WaypointSerializer, self).create(validated_data)
like image 802
andre Avatar asked Sep 27 '15 16:09

andre


1 Answers

In view you can override get_serializer_context method:

def get_serializer_context(self):
    return {"trip_id": self.kwargs['trip_id']}

and then in the serializer you can get it from self.context:

def create(self, validated_data):
    trip_id = self.context["trip_id"]
    validated_data['trip'] = Trip.objects.get(pk=trip_id)
    return super(WaypointSerializer, self).create(validated_data)
like image 111
M.Void Avatar answered Oct 10 '22 04:10

M.Void