我正在尝试使用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
答案 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)
答案 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
的精彩教程