django patch method to edit or update the user fields

i am using django and rest framework, I am unable to update the data(fields) from the PATCH method.If i click, every time its creating the new record. please find the code below;

data from postman:method - 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"
}

above data "company_id" is the primary key,i need to edit or update the record with the primary key. In PATCH method where i need to pass the primary key for edit or update the record.

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__'

Upvotes: 0

Views: 1397

Answers (1)

akhilsp
akhilsp

Reputation: 1103

You have to provide a model instance to update. Try something like:

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)

Upvotes: 1

Related Questions