5

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)

1 Answer 1

5

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

NOTE! since DRF 3.10 @list_route() decorator was removed, you should use @action(detail=False) instead, I used @action(detail=False, methods=['PATCH']) to bulk patch, for example Thank you @PolYarBear

Sign up to request clarification or add additional context in comments.

18 Comments

It got this error: Expected view NotificationEditAPIView to be called with a URL keyword argument named "id". Fix your URL conf, or set the .lookup_field attribute on the view correctly.
This is my new URL conf: url(r'^read_all/$', NotificationEditAPIView.as_view(), name='list'),
you don't need to change url config, just go by old way to list with prefix
url(r'^(?P<id>[0-9]+)/mark_as_read/$', NotificationEditAPIView.as_view(), name='list') just for one object but I want to update all objects, Brown.
why you use for list RetrieveUpdateAPIView why (for example) not ReadOnlyModelViewSet
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.