django rest framework : method override


Description

  • viewset の指定 method(create, updateなど) を上書きする

上書き

以下, 対応する method を上書きする

api/views.py
from rest_framework import viewsets
from rest_framework.response import Response

from api.models import User

from .serializers import UserSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().select_related()
    serializer_class = UserSerializer

    def list(self, request):
        # GET    :  /api/users/

    def create(self, request):
        # POST   :  /api/users/

    def retrieve(self, request, pk=None):
        # GET    :  /api/users/:id/

    def update(self, request, pk=None):
        # PUT    :  /api/users/:id/

    def partial_update(self, request, pk=None):
        # PATCH  :  /api/users/:id/

    def destroy(self, request, pk=None):
        # DELETE :  /api/users/:id/

list 実装例

api/views.py
from rest_framework import viewsets
from rest_framework.response import Response
from api.models import User

from .serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    list:
    Return a list of all the existing users.
    """

    queryset = User.objects.all().select_related()
    serializer_class = UserSerializer

    def list(self, request):
        """
        list:
        Return a list of all the existing users.
        """

        # 全 user 情報を取得し, serialize 
        data = UserSerializer(User.objects.all(), many=True).data

        # http response として返す
        return Response(status=200, data=data)

参考