在 Django 中验证 Json - Django Rest Framework

Validate Json in Django - Django Rest Framework

我需要验证以下内容 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必须是costbenefit 在 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 中是否有等效的方法?

是的,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