Building APIs with Django and Django Rest Framework (readthedocs.org)
More views and viewsets
A better URL structure
- 현 상태 : 3개의 API endpoint로 구성
- /polls, /polls/<pk>/
- /choices/
- /vote
- API를 계층적으로 다시 디자인하기
- /polls, /polls/<pk> : GET
- /polls/<pk>/choices : GET choices or CREATE choices
- /polls/<pk>/choices/<choice_pk>/vote : POST vote
Changing the views
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Poll, Choice
from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer
class PollList(generics.ListCreateAPIView):
queryset = Poll.objects.all()
serializer_class = PollSerializer
class PollDetail(generics.RetrieveDestroyAPIView):
queryset = Poll.objects.all()
serializer_class = PollSerializer
class Choicelist(generics.ListCreateAPIView):
def get_queryset(self):
queryset = Choice.objects.filter(poll_id=self.kwargs["pk"])
return queryset
serializer_class = ChoiceSerializer
class CreateVote(generics.CreateAPIView):
serializer_class = VoteSerializer
def post(self, request, pk, choice_pk):
voted_by = request.data.get("voted_by")
data = {"choice":choice_pk, 'poll':pk, 'voted_by':voted_by}
serializer = VoteSerializer(data=data)
if serializer.is_valid():
vote = serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ChoiceList와 CreateVote를 수정해주었다.
from django.urls import path
from .apiviews import PollViewSet, PollList, PollDetail, ChoiceList, CreateVote
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('polls', PollViewSet, basename='polls')
urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail"),
path("polls/<int:pk>/choices/", ChoiceList.as_view(), name="choice_list"),
path("polls/<int:pk>/choices/<int:choice_pk>/vote/", CreateVote.as_view(), name="create_vote"),
]
계획한대로 url pattern을 수정해준다.
Introducing Viewsets and Routers
from rest_framework import viewsets, generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Poll, Choice
from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer
class PollViewSet(viewsets.ModelViewSet):
queryset = Poll.objects.all()
serializer_class = PollSerializer
Choosing the base class to use
Next steps
- 엑세스 컨트롤
'Computer Science > BackEnd' 카테고리의 다른 글
Django for APIs | #2 Web APIs (1) | 2022.09.26 |
---|---|
Django for APIs | #0 Introduction (0) | 2022.09.18 |
Django API #4 | Views and Generic Views (0) | 2022.09.11 |
Django API #3 | Serializing and Deserializing Data (0) | 2022.09.11 |
장고 DRF #6 | Django REST framework ViewSets & Routers (0) | 2022.09.11 |