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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With