1

我有一个自定义操作,它获取输入并应返回分配的 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 模式即可。

4

1 回答 1

1

这里的技巧是 read_only/write_only 属性。

序列化程序必须如下所示:

class AssignmentSerializer(serializers.Serializer):
    hostname = serializers.CharField(required=False, write_only=True)
    useDefaultDomain = serializers.BooleanField(default=True, write_only=True, help_text='Use pools default domain')
    description = serializers.CharField(required=True, write_only=True)
    assignments = CIDRSerializer(many=True, read_only=True)

然后它可以像这样返回:

return Response(
    AssignmentSerializer(
        instance={
            'assignments': list(result.values())
        },
        read_only=True,
        context={'request': request}
    ).data,
    status=status.HTTP_201_CREATED
)
于 2021-03-03T12:49:57.983 回答