DEV Community

tobiadiks
tobiadiks

Posted on

How to update your database through django_rest_framework.

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)

Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay