我正在处理一个分配,该分配需要请求第三方API并占用一些响应并更新其密钥并呈现为DRF响应。
这可以通过串行器实现吗?
这是我在做什么。
response = BooksService().get_books()
transformed_data = self.transform_data(response)
return Response(transformed_data)
def transform_data(response):
data = response.json()
required_data = {
key_i_need_1 = data.get(KeyINeed1)
key_i_need_2 = data.get(KeyINeed2)
...
}
return required_data
答案 0 :(得分:0)
我认为您可以尝试做这样的事情。
Serializer仅尊重其中定义的字段,其他字段将忽略。
class ResponseSerializer(Serializer):
required_field1 = serializers.FieldType()
required_field2 = serializers.FieldType()
required_field3 = serializers.FieldType()
required_field4 = serializers.FieldType()
required_field5 = serializers.FieldType()
class Meta:
fields = (required_field1, required_field2, required_field3, required_field4, required_field5)
def view():
response = requests.get(external_api).json()
modified_response = ResponseSerializer(data=response)
return Response(modified_response.data)