Stay Hungry,Stay Foolish!

ModelViewSet supplementary

Marking extra actions for routing

https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing

ModelViewSet集成了 CRUD 所有功能, 如果使用此模型, 则后台数据处理逻辑被定死,

如果有新的定制逻辑, 则通过扩展方法来实现。

from django.contrib.auth.models import User
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(detail=True, methods=['post'])
    def set_password(self, request, pk=None):
        user = self.get_object()
        serializer = PasswordSerializer(data=request.data)
        if serializer.is_valid():
            user.set_password(serializer.validated_data['password'])
            user.save()
            return Response({'status': 'password set'})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False)
    def recent_users(self, request):
        recent_users = User.objects.all().order_by('-last_login')

        page = self.paginate_queryset(recent_users)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(recent_users, many=True)
        return Response(serializer.data)

 

例子

https://github.com/fanqingsong/draw_guess/blob/master/backend/chat/views.py

class CommentViewSet(viewsets.ModelViewSet):
    """
    """
    queryset = Comments.objects.all()
    serializer_class = CommentsSerializer

    @action(methods=['get'], detail=False)
    def query(self, request):
        # print("-------------------")
        # print(request.query_params)

        drawing = request.query_params["drawing"]
        # print("=====")
        # print(drawing)

        querydata = Comments.objects.filter(drawing=drawing).order_by('id')

        serializer = CommentsSerializer(querydata, many=True)

        return Response(serializer.data)

 

django model query

https://docs.djangoproject.com/en/3.2/topics/db/queries/#retrieving-specific-objects-with-filters

>>> Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime.date(2005, 1, 30)
... )

 

select_related and serializer

https://stackoverflow.com/questions/50996306/show-and-serialize-the-results-of-select-related-model-method

PostSerializer():
    user = UserSerializer()
    class Meta:
        model = Post
        fields = ('name', 'user')

 

posted @ 2021-11-13 22:51  lightsong  阅读(59)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel