[Django]-How to update in a single post multiple instances – django rest framework

3👍

Assuming you have a request payload as below,

{'payload' :[
    {
        "order": 4,
        "id": 1,
    },
    {
        "order": 2,
        "id": 2,
    }
]}

then try to change your views as below,

class RouteDispatchViewSet(viewsets.ModelViewSet):
    queryset = RouteDispatch.objects.all()
    serializer_class = RouteDispatchSerializer

    @list_route(methods=['post'], url_path='order')
    def order_dispatch(self, request):
        for data in request.data['payload']:
            self.queryset.filter(id=data['id']).update(order=data['order'])

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

Refference : Queryset update django

👤JPG

Leave a comment