我正在使用django和rest框架,我无法从PATCH方法更新数据(字段)。如果我点击,每次创建新记录。 请找到下面的代码;
邮递员的数据:方法 - PATCH{
"company_id": 2,
"company_code": "PR",
"company_name": "Padise",
"company_description": "company",
"company_address": "company",
"active": true,
"updated_by": null,
"updated_dtm": "2017-04-26T12:12:20Z"
}
以上数据" company_id"是主键,我需要使用主键编辑或更新记录。 在PATCH方法中,我需要传递主键进行编辑或更新记录。
views.py
class getCompanyDetails(APIView):
def get(self, request):
comp = company.objects.filter(active = True)
serializer = restGetCompanySerializer(comp, many=True)
return JsonResponse({"allCompanies":serializer.data})
def patch(self, request):
serializer = restAddCompanySerializer(data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
class restAddCompanySerializer(serializers.ModelSerializer):
class Meta:
model = company
fields = '__all__'
答案 0 :(得分:0)
您必须提供要更新的模型实例。尝试类似:
class getCompanyDetails(APIView):
def get(self, request):
comp = company.objects.filter(active = True)
serializer = restGetCompanySerializer(comp, many=True)
return JsonResponse({"allCompanies":serializer.data})
def patch(self, request):
# fetching company with given company_id
company = company.objects.get(pk=request.data['company_id'])
# passing company as first argument. This will invoke
# ModelSerializer's 'update' method instead of 'create' method.
serializer = restAddCompanySerializer(company, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)