4

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.

Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
Aman Gupta
  • 1,764
  • 4
  • 30
  • 58
  • What's the final result you're trying to achieve? Get these two querysets chained together and rendered as a single JSON list? – Alex Morozov Jan 08 '16 at 17:14
  • I want to get two separate list of samples(from the queryset) one submitted by the user and 2nd which are submitted by other users. – Aman Gupta Jan 08 '16 at 17:18
  • Sure, but what you gonna do with them next? Could you show us a sample "ideal" JSON? – Alex Morozov Jan 08 '16 at 17:34

2 Answers2

5

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)
Alex Morozov
  • 5,823
  • 24
  • 28
  • Extremly soory for being late , as i lost my net connectivity. Once i return queryset and queryset1 from here, i want to access these two separatly.i.e if i chain these two objects, is there any way i can unchain them. i will be using them in a Javascript file. – Aman Gupta Jan 09 '16 at 12:58
  • @AmanGupta if you got the solution then please comment here.I also want to return two queryset objects by get_queryset but unable to do so. – Nishant sharma Dec 30 '17 at 17:14
2

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)
Mr Singh
  • 3,936
  • 5
  • 41
  • 60