Bulk Update data in Django Rest Framework

Kit*_*Kit 5 python django python-3.x django-rest-framework

I am creating a Notification apps by Django Rest Framework which users can MARK AS READ ALL notification by using PATCH API in frontend. How can I Bulk Update data can do this task.

This serializer and viewset below just for PATCH only one notification object, but I want to do it all with Notifications which have field is_read = False

Edited with the right way

My Serializers:

class NotificationEditSerializer(ModelSerializer):
    class Meta:
        model = Notification
        fields = (
            'id',
            'is_read'
        )
Run Code Online (Sandbox Code Playgroud)

My Viewset:

from rest_framework.response import Response
class NotificationListAPIView(ReadOnlyModelViewSet):
    queryset = Notification.objects.all()
    permission_classes = [AllowAny]
    serializer_class = NotificationEditSerializer
    lookup_field = 'id'

    @list_route(methods=['PATCH'])
    def read_all(self, request):
        qs = Notification.objects.filter(is_read=False)
        qs.update(is_read=True)
        serializer = self.get_serializer(qs, many=True)
        return Response(serializer.data)
Run Code Online (Sandbox Code Playgroud)

My URL:

from rest_framework import routers
router.register(r'notifications/read_all', NotificationListAPIView)
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试使用list_route例如:

from rest_framework.response import Response
from rest_framework.decorators import list_route

class NotificationListAPIView(ReadOnlyModelViewSet):
    #YOUR PARAMS HERE

    @list_route()
    def read_all(self, request):
        qs = Notification.objects.filter(is_read=False)
        qs.update(is_read=True)
        serializer = self.get_serializer(qs, many=True)
        return Response(serializer.data)
Run Code Online (Sandbox Code Playgroud)

该 api 可通过^YOUCURRENTURL/read_all/$更多详细信息Marking-extra-actions-for-routing获得

笔记!由于DRF 3.10 @list_route()装饰器已被删除,您应该使用@action(detail=False)它,我曾经使用@action(detail=False, methods=['PATCH'])批量补丁,例如谢谢@PolYarBear