我已经使用django序列化程序已有一段时间了,而且好像每次我使用put / post / patch发送有效负载时,serializers.is_valid()
只会检查有效负载数据属性类型是否正确,必需存在并且不检查models.py
假设我有models.py :
class Task(models.Model):
title = models.CharField(max_length=100, default='default_task_name')
description = models.CharField(max_length=1000, blank=True, default='')
complete = models.BooleanField(default=False)
canceled = models.BooleanField(default=False)
date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('id', 'date')
在我的serializers.py
中,我有以下内容:
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'
在我的views.py
中,我有以下内容:
class TaskDetails(APIView):
def get_object(self, pk):
try:
return Task.objects.get(pk=pk)
except Task.DoesNotExist:
raise Http404
def put(self, request, pk):
data = JSONParser().parse(request)
serializer = TaskSerializer(self.get_object(pk), data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=HTTP_422_UNPROCESSABLE_ENTITY)
使用cURL
:
curl -X PUT -H "Content-Type: application/json" -d '{"title":"task_1", "description":"learning rest", "task_force":"undefined "}' "my_api_uri"
我除了得到这样的错误:
'errors': {'task_force': ['undefined attribute task_force'], 'status_code': '422'}
由于有效载荷包含的是在model.py或serializers.py内部未定义的task_force
但是我得到的响应没有错误:
{data={"title":"task_1", "description":"learning rest", "task_force":"undefined "}, "status_code": '201'}
`
使用序列化程序进行检查的解决方法是什么?