我有一个简单的更新 api,但无法正常工作。我通过仅发送需要更新的密钥和数据来测试邮递员中的 API,但我的前端正在发送整个表单数据以及更新的数据。当我仅发送密钥和需要更新的数据时,它在我的邮递员中工作,但是当我将某些字段的所有数据作为空字符串
("")
发送时,它不会更新。
我的模特:
class Lead(models.Model):
title = models.CharField(max_length=5, choices=TITLES, blank=True)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30)
address = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=50, blank=True)
state = models.CharField(max_length=50, blank=True)
country = models.CharField(max_length=30, default="nepal")
phone = models.CharField(max_length=50, )
/........other fields................................/
我的看法:
class LeadsView(APIView):
permission_classes = [AllowAny]
def put(self, request, pk=None, *args, **kwargs):
print("iam put")
id = pk
abc = Lead.objects.get(id=id)
serializer = LeadSerializer(abc,data=request.data)
if serializer.is_valid():
serializer.save()
return Response({
"message": " Leads has been updated",
"data": serializer.data
}, status=status.HTTP_200_OK)
return Response(serializer.data)
我的序列化器:
class LeadSerializer(serializers.ModelSerializer):
email= serializers.EmailField(required=False)
phone = serializers.CharField(required=False)
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
title = serializers.CharField(required=False)
address = serializers.CharField(required=False)
company_name = serializers.CharField(required=False)
/.................same in other fields............../
class Meta:
model = Lead
fields = ['id','title','first_name','last_name','address','company_name',
'city','state','country','phone','source','mobile',
'email','gender','date_created','lead_status']
在序列化器级别中,我已将所有字段设置为必需= false,但在模型级别中,仅需要三个字段first_name、last_name和phone,其他字段可以为空。
当所有字段都存在时,它会更新,当某些字段为空字符串时,它不会更新。另外,当仅发送一个密钥+数据时,它会被更新。
这是因为您的序列化器在验证请求数据时无效。在这一行中:
if serializer.is_valid():
pass
更改为:
if serializer.is_valid(raise_exception=True):
pass
您将收到引发验证错误、有关请求数据的详细信息。
就是这么简单。您只需更换:
def put(self, request, pk=None, *args, **kwargs):
instance = self.get_object()
serializer = LeadSerializer(instance,data=request.data, partial=False)
if serializer.is_valid(raise_exception=True):
serializer.update(instance, serializer.validated_data)
self.perform_update(serializer)
return Response({
"message": " Leads has been updated",
"data": serializer.data
}, status=status.HTTP_200_OK)
return Response(serializer.data)
更换
serializer.save()
至
serializer.update(instance, serializer.validated_data)