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)
For partial
updateyou can usePATCHmethod instead of usingPUTbasically
PUTmethod needs to full object for update andPATCHmethod 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.
------
PUTvsPATCH-------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 entityPATCH:allows the modification of an entity of a resource. So, it can be applied to change only particular portions of an entity's dataso, in request decorator put
PATCHmethod instead ofPUTlike this...views.py