我有一个自定义操作,它获取输入并应返回分配的 cidr 对象列表。
@action(detail=True, methods=['POST'], name="Assign Subnet from Pool", serializer_class=AssignmentSerializer)
def assign(self, request, pk=None):
"""Adds a new address within the pool
"""
pool = self.get_object()
serializer = AssignmentSerializer(data=request.data)
if not serializer.is_valid():
return Response(status=status.HTTP_412_PRECONDITION_FAILED)
# Computation generating a dictionary with cidr objects (result)
# Successfully assigned
serializer.save(assignments=[cidr for cidr in result.values()])
return Response(serializer.data, status=status.HTTP_201_CREATED)
我的序列化器看起来像这样
class AssignmentSerializer(serializers.Serializer):
"""This is a serializer for a custom form
"""
hostname = serializers.CharField(required=False)
useDefaultDomain = serializers.BooleanField(default=True, help_text='Use pools default domain')
description = serializers.CharField(required=True)
assignments = CIDRSerializer(many=True, required=False, help_text='Will not be evaluated on request but contain the assignments in the response')
但是,我还没有弄清楚如何在响应中包含分配。序列化程序不需要将它们持久化到数据库中,只需要使用序列化程序自动生成 openapi 模式即可。