简体   繁体   中英

How to return multiple queryset object or add queryset result from get_queryset method in Django

In my django application i have defined a ViewSet which has a get_queryset method as this :

class SampleViewSet(ReadOnlyModelViewSet):
    serializer_class = SampleSerializer
    permission_classes = (IsAuthorizedToAccess, )

    def get_queryset(self):
        queryset = Sample.objects.filter(submitted_by=self.request.user.id)
        queryset1 = Sample.objects.filter(submitted_by!=self.request.user.id) 
        return queryset

This way i have two queryset objects 1st where samples are submitted by the user and 2nd where samples which are submitted by other users. This SampleViewSet is called from an ajax request where i use the returned queryset object.

Can you please help how can i return both the objects.

For what i tried is i print the queryset object and tried fooling django by creating json object similar to the queryset.But it seems like django is quite intelligent in catching that.

EDIT: The question is should i look for an alternate method of get_queryset like list() [From Django Rest framework ] and return the json with Httpresponse or is there a real solution to either club two queryset object and return from here.

Until the author hasn't refined the question, the first guess is:

from itertools import chain

def get_queryset(self):
    queryset = Sample.objects.filter(submitted_by=self.request.user.id)
    queryset1 = Sample.objects.filter(submitted_by!=self.request.user.id) 
    return chain(queryset, queryset1)

without chain you can manage like this:

def list(self, request):
    client = Client.objects.all()
    server = Server.objects.all()
    serializer1 = self.serializer_class(server, many=True)
    serializer2 = self.serializer_class(client, many=True)
    Serializer_list = [serializer1.data, serializer2.data]
    return Response(Serializer_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM