django 验证选择字段DRF

piah890a  于 2023-05-01  发布在  Go
关注(0)|答案(1)|浏览(117)

嗨,我有我的模型和它的序列化器,我在测试时发现,无论我在我的选择字段中有什么,序列化器都会被保存,但在Django管理员选择字段中,当数据错误时为空,当数据正确时,我可以看到正确的选项
所以,

-> wrong choice data
-> saved regardless 
-> nothing in django admin
-> correct choice data
-> saved
-> correct value in django admin

如果我检测到用户发布了不正确的数据,我如何返回验证错误?
我尝试的是

topic = serializers.ChoiceField(choices=School.topic)

我不认为遍历每个元组并搜索字符串是正确或有效的
代码

class SchoolViewSet(viewsets.ModelViewSet):

    queryset = School.objects.all()
    serializer_class = SchoolSerializer

    def create(self, request):
        serializer = SchoolSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class School(models.Model):

    SUBJECT = (
       ('Math', 'Mathematic'),
       ('Eng', 'English'),
       ('Cesolved', 'Chemistry'),
   )

    name = models.CharField(blank=False, max_length=50)
    subject = models.CharField(choices=SUBJECT, max_length=15, blank=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(f'{self.name} is {self.subject}')
class SchoolSerializer(serializers.ModelSerializer):
    subject = serializers.ChoiceField(choices=School.SUBJECT)

    def validate(self, data):
        name = data["name"]
        if (5 > len(name)):
            raise serializers.ValidationError({"IError": "Invalid name"})
 
        return data

    class Meta:
        model = School
        fields = "__all__"
46qrfjad

46qrfjad1#

我已经找到了检查序列化器中传递的选择是否正确的版本。

请告诉我是否有更好的方法

基本上,我已经将我的选择字段从模型导入序列化器,然后将其转换为dict,然后在validate函数中检查值是否存在

CHOICE_DICT = dict(School.SUBJECT)

def validate(self, data):

   choice = data["subject"]
   if not (choice in CHOICE_DICT):
      raise serializers.ValidationError({"Invalid Choice": f"Choice field is not valid. Valid choices {Contact.School}"})

        return data

我不认为这是最快的方法。

相关问题