简体   繁体   English

如何从Django中的get_queryset方法返回多个queryset对象或添加queryset结果

[英]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 : 在我的django应用程序中,我定义了一个ViewSet,它有一个get_queryset方法,如下所示:

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. 从ajax请求调用此SampleViewSet,其中我使用返回的queryset对象。

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. 我试过的是我打印queryset对象并尝试通过创建类似于queryset的json对象来欺骗django。但是看起来django在捕获它时非常聪明。

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. 编辑:问题是我应该寻找get_queryset的替代方法,如list()[来自Django Rest框架]并返回带有Httpresponse的json,或者是否有一个真正的解决方案,要么来自两个查询集对象并从这里返回。

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: 没有chain你可以像这样管理:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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