在将数据传递给序列化程序django api时添加额外的上下文

时间:2017-09-25 20:47:21

标签: python django api serialization django-rest-framework

我正在尝试使用request.data在我的表格中添加一个额外的字段auth_token,但它会出错。错误是 - data['auth_token_id'] = auth_token TypeError: list indices must be integers or slices, not str

我的代码如下:

serializers.py

class AppSerializer(serializers.ModelSerializer):

  class Meta:
     model = ThirdPartyApps
     fields = ('app_name', 'package_name', 'auth_token_id')

views.py

@api_view(['POST'])
def add_apps(request):
    data = request.data
    auth_token = request.META.get('HTTP_AUTHTOKEN', '')
    data['auth_token_id'] = auth_token
    serializer = AppSerializer(data=data, many=True)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    else:
        return Response(serializer.errors)

我正在寻找一种通过序列化器传递额外数据的方法。 我只想将auth_token添加到我的模型中,就像request.data一样,但是它给出了这个错误 -

data['auth_token_id'] = auth_token TypeError: list indices must be integers or slices, not str

3 个答案:

答案 0 :(得分:3)

您应该将其作为上下文传递:

serializers.py

class AppSerializer(serializers.ModelSerializer):
    auth_token_id = serializers.SerializerMethodField()
    def get_auth_token_id(self, obj):
        if "auth_token_id" in self.context:
            return self.context["auth_token_id"]
        return None
    class Meta:
         model = ThirdPartyApps
         fields = ('app_name', 'package_name', 'auth_token_id')

views.py

@api_view(['POST'])
def add_apps(request):
    data = request.data
    auth_token = request.META.get('HTTP_AUTHTOKEN', '')
    serializer = AppSerializer(data=data, many=True, context = {"auth_token_id": auth_token})
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    else:
        return Response(serializer.errors)

答案 1 :(得分:1)

您也可以将值发送到序列化程序的保存方法

{{1}}

请参阅此处的文档:Properties.load()

答案 2 :(得分:0)

我们还可以使用基于基于类的视图,例如:

class AddApp(APIView):
      def post(request):
        data = request.data
        auth_token = request.META.get('HTTP_AUTHTOKEN', '')
        serializer = AppSerializer(data=data, many=True)
        if serializer.is_valid():
            serializer.save(auth_token_id=auth_token)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors)

另请参阅有关该主题here

的精彩教程