Last week I came across questions on how to update your database through REST API reason is because most of them faced one issue or the other.
Here is a snippet that works via using a decorator
views.py
from rest_framework.decorator import api_view
from rest_framework.response import Response
from .models import my_model
from .serializer import mySerializer
@api_view(['GET','PUT'])
def updateDb(request, pk):
try:
model = my_model.objects.get(pk=pk)
except:
return.Response('Not Found')
if request.method == 'PUT':
serializer = mySerializer(model, request.data)
if serializer.is_valid():
serializer.save()
return Response ("Updated")
else:
return Response ("Failed")
if request.method == 'GET':
serializer=mySerializer (models)
return Response (serializer.data)
Top comments (0)