example-of-crud-in-django-w.../app/libros/views.py

40 lines
1.2 KiB
Python
Raw Normal View History

2021-07-12 07:01:26 +02:00
# app/libros/views.py
2021-07-05 15:56:53 +02:00
from django.http import JsonResponse
2021-07-12 23:47:31 +02:00
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import LibroSerializer
from .models import Libros
2021-07-05 15:56:53 +02:00
def ping(request):
data = {"ping": "pong!"}
return JsonResponse(data)
2021-07-12 07:01:26 +02:00
class LibrosList(APIView):
2021-07-12 23:47:31 +02:00
def get(self, request, format=None):
libros = Libros.objects.all().order_by('created_at')
serializer = LibroSerializer(libros, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
2021-07-12 07:01:26 +02:00
def post(self, request):
serializer = LibroSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
2021-07-12 23:47:31 +02:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class LibrosDetails(APIView):
def get(self, request, pk, format=None):
libro = Libros.objects.filter(pk=pk).first()
serializer = LibroSerializer(libro)
if libro:
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)