Django Rest Framework中的批量更新数据

时间:2017-12-20 09:39:15

标签: python django python-3.x django-rest-framework

我正在通过Django Rest Framework创建一个Notification应用程序,用户可以通过在前端使用PATCH API MARK AS READ ALL通知。如何批量更新数据可以完成此任务。

下面的序列化程序和视图集仅适用于PATCH一个通知对象,但我想使用包含字段is_read = False

的通知进行所有操作

以正确的方式编辑

我的序列化器:

class NotificationEditSerializer(ModelSerializer):
    class Meta:
        model = Notification
        fields = (
            'id',
            'is_read'
        )

我的观点:

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)

我的网址:

from rest_framework import routers
router.register(r'notifications/read_all', NotificationListAPIView)

1 个答案:

答案 0 :(得分:3)

您可以尝试使用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)

api可通过^YOUCURRENTURL/read_all/$更多详情marking-extra-actions-for-routing

获取