0

我需要验证以下 JSON:

{
    "monday": [
        //List of MyClass object
    ],
    "tuesday": [
        //List of MyClass Object
    ],
    "wednesday": [
        //List of MyClass Object
    ],
    ......
}

我需要检查它是否包含任何不是一周中某一天的键(例如,mondai、thudai)。也MyClass被定义为:

class MyClass(models.Model):
    type = models.CharField(unique=True, max_length=20)
    value = models.IntegerField()

该字段value必须是一个正整数并且不能超过 10000。此外,type必须是cost或者benefit 在 Scala 中我会使用以下内容:

object MyClass {
  val ALLOWED_TYPES = Seq[String]("cost", "benefit")
  implicit val openingHourReads: Reads[OpeningHour] = (
    (JsPath \ "type").read[String].filter(JsonValidationError("Type must be cost or benefit"))(ALLOWED_TYPES.contains(_))  and
      (JsPath \ "value").read[Int](min(1).keepAnd(max(10000)))

    )(MyClass.apply _)

Django中有等效的方法吗?

4

1 回答 1

1

是的,在 django 中有类似的方法:

在模型级别限制输入数据(问题#1):

# models.py
from django.core.validators import MaxValueValidator

class MyClass(models.Model):
    VALUE_CHOICES = [
        ('COST', 'cost'),
        ('BENEFIT', 'benefit')
    ]
    class_type = models.CharField(choices=VALUE_CHOICES,unique=True)
    value = models.IntegerField(validators=[MaxValueValidator(limit_value=10000)])

在序列化程序级别限制输入数据(问题#2):

# serializers.py
from .models import MyClass
from rest_framework import serializers
class MyClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyClass
        fields = '__all__'

class MainSerializer(serializers.Serializer):
    day = serializers.ChoiceField(choices=['monday', 'tuesday', 'wednesday'])
    my_class = serializers.ListField(child=MyClassSerializer(many=True))

最后,您需要封装数据以使其通用:

# views.py or any other place you like
from .serializers import MainSerializer

your_json = {
    "monday": [
       //List of MyClass object
    ],
    "tuesday": [
        //List of MyClass Object
    ],
    "wednesday": [
        //List of MyClass Object
    ],
    ......
}
json_array = []

for key, value in your_json:
    json_array.append({'day':key, 'my_class':value})

serializer = MainSerializer(data=json_array, many=True)

serializer.is_valid() # this will tell you if your data is valid or not 
于 2020-01-14T19:17:11.180 回答