if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
如何在serializer.data dict中添加一个额外的字段(非模型字段)?我想在发送响应之前添加(“status”:“available”)。我试过了 -
if serializer.is_valid():
serializer.save()
## This one doesn't work as serializer.data is of the type 'ReturnDict'
serializer.data.append(("status","available"))
## OR
serializer.data["status"] = "available"
return Response(serializer.data, status=status.HTTP_201_CREATED)
我还想在发送响应之前修改serializer.data的字段名称。有没有办法做到这一点?
答案 0 :(得分:7)
您可以在序列化程序中添加一个额外的字段,如下所示:
class MySerializer(serializers.ModelSerializer)
status = serializers.SerializerMethodField('get_status')
class Meta:
model = MyModel
read_only_fields = ('status',)
def get_status(self, obj):
""" Get the current objects status """
if obj.available == 1:
return 'available'
else:
return 'not available'
更改字段名称的一种方法是使用中间件类来格式化响应。如果我必须格式化整个API的响应,我会这样做。