2👍
You can use detail_route
or list_route
decorators.
from rest_framework.decorators import list_route
class MessageViewSet(viewsets.ModelViewSet):
@list_route()
def mark_read(self, request):
queryset = Message.objects.update(isread=True)
return Response({'read':queryset})
With that mark_read
method will be available at api/get_messages/mark_read
. And you don’t need to create separate router, just use one you created for MessageViewSet
2👍
Since you are using a model viewset you can directly use put or patch rest method to send the desired value for the desired field as the data.
Ideally in rest get should not change model values. If you really want a different end point put the list_route or detail_route decorator on your mark_read method, and make them a valid call for only a put and/or patch call
from rest_framework.decorators import list_route
class MessageViewSet(viewsets.ModelViewSet):
@list_route(methods=['Patch', 'PUT'])
def mark_read(self, request):
queryset = Message.objects.update(isread=True)
return Response({'read':queryset})
0👍
Thanks to @ivan-semochkin and @Shaumux for replies. Advices were really helpful.
That is my route. I used detail_route instead of list_route.
@detail_route(methods=['get','put'], url_name='mark_read/')
def mark_read(self, request, pk=None):
queryset = Message.objects.filter(pk=pk).update(isread=True)
return Response({'read':queryset})
Now ‘isread’ value is changing wnen i visit ‘mark_read’ page.
Link: “api/get_messages/pk/mark_read”
Does anyone know, is it posslible to make links looking the next way:
“api/get_messages” – list, “api/mark_read/pk” – changing isread value.
Is it possible to create something like this? “api/mark_read?=pk”