在POST方法中创建和对象时,如何只返回创建对象的几个字段?这取自文档:
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
此处serializer.data
包含序列化程序中定义的所有字段,但我只想返回其中的一些字段。
答案 0 :(得分:5)
我在这里看到了多个可能性: 首先(我最喜欢的)是将请求对象发送到序列化器,然后序列化器将动态选择你想要的字段:
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data,context={'request': request})
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
然后在序列化器中:
class SnippetSerializer(serializers.IDontKnow):
class Meta:
model = YourModel
fields = ('url', 'field1','field2','field3')
write_only_fields = ()
def __init__(self, *args, **kwargs):
super(SnippetSerializer, self).__init__(*args, **kwargs)
if self.context != {}:
request = self.context['request']
if request.method == 'POST':
self.write_only_fields = {'field1':self.fields['field1'], 'field3':self.fields['field3']}
这应该使field1和field3只能写,所以他们不会被退回。
其次,也许更简单的解决方案是定义其他序列化器,对于post方法是唯一的:
def post(self, request, format=None):
serializer = PostSnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
您可以指定哪个字段不会被重新调整:
class PostSnippetSerializer(serializers.IDontKnow):
class Meta:
model = YourModel
fields = ('url', 'field1','field2','field3')
write_only_fields = ('field1','field3')
field1和field 3不会作为回应返回,
第三种方法是在您的视图中直接创建您的回复:
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
results = {'url': serializer.data['url'],'field2':serializer.data['field2']}
return Response(results, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这将仅返回url和field2,因此将保存field1和field3但不会返回。
答案 1 :(得分:3)
对于其他拥有相同问题的人,这是what Tom Christie has said:
要么:
- 考虑在您不希望作为输出的字段上使用write_only = True。
- 使用其他序列化程序将响应返回到用于验证的响应。
- 只需直接返回响应数据,而无需使用序列化程序。