demo-hackernews-with-django.../app/api/views.py

30 lines
911 B
Python
Raw Permalink Normal View History

2021-06-22 15:43:26 +02:00
from app.api.models import News
2021-06-23 15:10:44 +02:00
from rest_framework import viewsets, mixins
2021-06-22 15:43:26 +02:00
from app.api.serializers import NewsSerializer
2021-06-23 15:10:44 +02:00
from rest_framework.response import Response
2021-06-25 14:25:14 +02:00
import json
2021-06-22 15:43:26 +02:00
2021-06-23 15:10:44 +02:00
class NewsViewSet( mixins.UpdateModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
2021-06-22 15:43:26 +02:00
"""
API endpoint that allows News to be viewed or edited.
"""
2021-06-23 15:10:44 +02:00
serializer_class = NewsSerializer
2021-06-22 15:43:26 +02:00
queryset = News.objects.all()
2021-06-23 15:10:44 +02:00
basename = "news"
def get(self, request):
serializer = NewsSerializer(self.queryset, many=True)
return Response(serializer.data)
2021-06-25 14:25:14 +02:00
def put(self, request):
2021-06-23 15:10:44 +02:00
# Update
2021-06-25 14:25:14 +02:00
my_news = News.objects.get(pk=request.data['id'])
2021-06-23 15:10:44 +02:00
my_news.votes = my_news.votes + 1
my_news.save()
# Devolvemos la noticia modificada
2021-06-25 14:25:14 +02:00
serializer = NewsSerializer(my_news)
2021-06-23 15:10:44 +02:00
return Response(serializer.data)