0

无法在 post body 参数的 swagger-ui 中显示 json 数组字段。我有带有 JsonField 列的 django 模型,列名显示在 swagger ui 中,但无法显示在 json 值中。请您提出您的建议。

#models
class Sample(models.Model):
    ApiUser = models.CharField(max_length=100)
    ApiKey = models.CharField(max_length=100)
    create_array = models.JSONField()
    UserName = models.CharField(max_length=100, blank=True, null=True)
    IPAddress = models.CharField(max_length=100, blank=True, null=True)

#serializers
class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sample
        fields = ('ApiUser','ApiKey','create_array','UserName','IPAddress')

对于使用上述模型和序列化程序,我有以下请求正文,

{
  "ApiUser": "string",
  "ApiKey": "string",
  "create_array": {},
  "UserName": "string",
  "IPAddress": "string"
}

但预期的输出是,

{
  "ApiUser": "string",
  "ApiKey": "string",
  "create_array": [{
  "name": "string",
  "id": "string", 
}],
  "UserName": "string",
  "IPAddress": "string"
}

在此处输入图像描述

4

1 回答 1

0

您可以扩展serializers.JSONField类(docs)。这将使您的序列化程序看起来像这样:

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sample
        fields = ('ApiUser','ApiKey','create_array','UserName','IPAddress')

    class createArrayJSONField(serializer.JSONField):
        class Meta:
            swagger_schema_fields = {
                "type": openapi.TYPE_OBJECT,
                "properties": {
                    "name": openapi.Schema(
                        type=openapi.TYPE_STRING,
                    ),
                    "id": openapi.Schema(
                        type=openapi.TYPE_STRING,
                    ),
                },
                "required": ["name", "id"],
             }

    create_array = createArrayJSONField()
于 2022-01-18T15:18:32.540 回答