Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Update data in 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'
        )

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)

My URL:

from rest_framework import routers
router.register(r'notifications/read_all', NotificationListAPIView)
like image 540
KitKit Avatar asked Dec 20 '17 09:12

KitKit


1 Answers

You can try to use list_route for example:

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)

the api is available by ^YOUCURRENTURL/read_all/$ more details marking-extra-actions-for-routing

like image 63
Brown Bear Avatar answered Oct 07 '22 04:10

Brown Bear