django 如何在rest_framework中使用序列化器验证JSON

juud5qan  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(120)

我在弄清楚如何使用rest框架序列化一个int、string和bool值列表时遇到了麻烦。

{
    "start_hour": "14:02:26",
    "DEVICE_INFO": [
        "0101",
        13
    ]
}

我试过ListSerializer()ListField()

from rest_framework import serializers

class SensairValidateFormSerializer(serializers.Serializer):
    start_hour = serializers.CharField(required=True)
    device_info = serializers.ListField(
        child=serializers.ListSerializer([
            serializers.CharField(required=True),
            serializers.BooleanField(required=True),
        ]),
        required=False
    )
kwvwclae

kwvwclae1#

您可以尝试使用SerializerMethodField()

from rest_framework import serializers

class SensairValidateFormSerializer(serializers.Serializer):
    start_hour = serializers.TimeField(format='%H:%M:%S', required=True)
    device_info = serilaizers.SerializerMethodField()

    def get_device_info(self, obj):
        # handle the object as you see fit here

我还将start_hour定义为TimeField,以确保输入字符串被格式化为时间。format属性设置为%H:%M:%S,以匹配输入字符串的格式。

相关问题