Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return list of ids in a Get. Django Rest Framework

I have a model called "document-detail-sample" and when you call it with a GET, something like this, GET https://url/document-detail-sample/ then you get every "document-detail-sample".

Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy.

But... the front-end Developers don't want to do it :D they say it's too much work...

So, I gotta return the id list. :D

I was thinking something like GET https://url/document-detail-sample/id-list

But I don't know how to return just a list. I read this post and I know how to get the id_list in the backend. But I don't know what should I implement to just return a list in that url...

the view that I have it's pretty easy:

class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
    queryset = DocumentDetailSample.objects.all()
    serializer_class = DocumentDetailSampleSerializer

and the url is so:

router.register(r'document-detail-sample', DocumentDetailSampleViewSet)

so:

1- is a good Idea do it with an url like .../document-detail-sample/id-list" ?

2- if yes, how can I do it?

3- if not, what should I do then?

like image 532
Chuck Aguilar Avatar asked Jan 25 '17 11:01

Chuck Aguilar


2 Answers

You could use @list_route decorator

from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response

class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
    queryset = DocumentDetailSample.objects.all()
    serializer_class = DocumentDetailSampleSerializer

    @list_route()
    def id_list(self, request):
        q = self.get_queryset().values('id')
        return Response(list(q))

This decorator allows you provide additional endpoint with the same name as a method. /document-detail-sample/id_list/
reference to docs about extra actions in a viewset

like image 175
Ivan Semochkin Avatar answered Oct 10 '22 22:10

Ivan Semochkin


Assuming you don't need pagination, just override the list method like so

class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
    queryset = DocumentDetailSample.objects.all()
    serializer_class = DocumentDetailSampleSerializer


    def list(self, request):
        return Response(self.get_queryset().values_list("id", flat=True))
like image 39
pragman Avatar answered Oct 10 '22 23:10

pragman