使用list序列化输入数据[Django restframework]

llmtgqce  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(123)

我对声明输入数据有疑问

{

  “id”: 1235,
  “products”:[
      { “product_id”: 1,
     “descriptions”: “b” },
      { “product_id”: 2,
    “descriptions”: “a” },
    
      { “product_id”: 3,
     “descriptions”: “c” }
    ]
}

所以我把序列化器做成这样

id = serializers.CharField(write_only=True, required=true)
product_id= serializers.Integer()(required=False)
descriptions = serializers.CharField(max_lenght=300)<br>
products = [serializer.JSONField()]

对不对?谢谢大家
如何获取一个数据列表的django序列化器

svdrlsy4

svdrlsy41#

您必须创建2个序列化程序类,其中第一个用于序列化单个产品和相关字段:

class ProductSerializer(serializers.Serializer):
    id = serializers.CharField(write_only=True, required=True)
    product_id= serializers.IntegerField(required=False)
    descriptions = serializers.CharField(max_lenght=300)

结果是这样的:

{ “product_id”: 1,
  “descriptions”: “b” }

你的另一个序列化器是上述数据的listSerializer,其中每一个都是这个列表的子列表:
一个二个一个一个
最终结果:

class ProductSerializer(serializers.Serializer):
    id = serializers.CharField(write_only=True, required=True)
    product_id= serializers.IntegerField(required=False)
    descriptions = serializers.CharField(max_lenght=300)

class ListProductSerializer(serializers.Serializer):
    products = serializers.ListField(child=ProductSerializer())
{
  “products”:[
      { “product_id”: 1,
  “descriptions”: “b” },
      { “product_id”: 2,
  “descriptions”: “a” }    
    ]
}

相关问题