1

I have a model and with DRF I want update only 2 field in model but when I update , 2 field are update but the other fields are empty .

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, format=None):
    try:
        requestd = request.POST['card_number']
        requestd2 = card.models.Card(card_number=requestd)
        #snippet = Card.objects.get()
        print(requestd2)
        credit = Card.objects.filter(card_number=requestd).values('initial_credit')
        credit2 = int(credit[0]['initial_credit'])
        requestcredit = int(request.POST['initial_credit'])
        #print(snippet)
        print(credit)
        print(credit2)


    except Card.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'PUT':
        serializer = CardModelSerializer(requestd2, data=request.data, partial=True) #insted of requestd 2 was snippet
        if serializer.is_valid():
            #print(request.data)
            new_credit= credit2 - requestcredit
            comment = 'اعتبار کافی نمی باشد .'
            comment2 = 'مقدار وارد شده صحیح نمی باشد'
            if new_credit >= 0:
                if requestcredit >0:
                    serializer.save()
                    return Response(serializer.data,status=status.HTTP_200_OK)
                else:
                    return Response (comment2, status=status.HTTP_400_BAD_REQUEST)
            else:

                return  Response(comment, status=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

2 Answers2

2

For partial update you can use PATCH method instead of using PUT

basically PUT method needs to full object for update and PATCH method only needs those fields which you want to update.

so, you need to use PATCH method to update only two fields that you want to update.

------ PUT vs PATCH -------

PUT: sends an enclosed entity of a resource to the server. If the entity already exists, the server updates its data. Otherwise, the server creates a new entity

PATCH: allows the modification of an entity of a resource. So, it can be applied to change only particular portions of an entity's data

so, in request decorator put PATCH method instead of PUT like this...

views.py

@api_view(['GET', 'PATCH', 'DELETE'])
def snippet_detail(request, format=None):
0

just put the data you want to leave behind before running serializer.save()

    request.data["name"] = requestd2.name
    request.data["name"] = requestd2.name
    request.data["name"] = requestd2.name
    serializer = CardModelSerializer(requestd2, data=request.data, partial=True) #insted of requestd 2 was snippet
    if serializer.is_valid():
chea
  • 101
  • 1
  • 11