简体   繁体   English

Django-rest-framework序列化多个没有相关字段的查询

[英]Django-rest-framework serializing multiple queries without a related field

I have looked around for the past few days and couldn't find a good way to do this. 在过去的几天里,我一直在环顾四周,找不到解决此问题的好方法。 I found a couple other threads but nothing seemed to work the way I needed it to. 我找到了其他几个线程,但是似乎没有任何方法可以按我需要的方式工作。

Here is the problem: I want to be able to serialize the result of multiple queries to return to the user so they don't have to connect to the API at multiple endpoints and so the server can do all of the heavy lifting when necessary. 这是问题所在:我希望能够序列化多个查询的结果以返回给用户,这样他们就不必在多个端点上连接到API,因此服务器可以在必要时进行所有繁重的工作。

I'm using APIView and a get request in views.py. 我在views.py中使用API​​View和get请求。

I have tried using chain from itertools but I can't seem to access the data from the serializer in any way. 我曾尝试使用itertools中的chain,但似乎无法以任何方式访问序列化器中的数据。 I have tried passing in a dictionary containing the results of the two queries and that didn't seem to work either. 我尝试传递包含两个查询结果的字典,但似乎也不起作用。

There is probably a really simple way of solving this but I can't seem to find any documentation on it. 解决这个问题的方法可能很简单,但是我似乎找不到任何文档。

This is a simplified piece of code so someone could answer easily: 这是一段简化的代码,因此有人可以轻松回答:

views.py views.py

class ModelOutputList(APIView):
    def get(self, request):
        data = self.get_queryset()
        serializer = ModelOutputSerializer(
            data,
            many=True
        )

        return Response(serializer.data)

    def get_queryset(self):
        model1 = Model1.objects.all()
        model2 = Model2.objects.all()

        data = list(itertools.chain(model1, model2))

        return data

serializers.py serializers.py

class ModelOutputSerializer(serializers.Serializer):
    model1 = Model1Serializer(many=True)
    model2 = Model2Serializer(many=True)

    class Meta:
        fields = ('model1', 'model2')

As always, any help would be greatly appreciated. 一如既往,任何帮助将不胜感激。

Try this: 尝试这个:

views.py views.py

class ModelOutputList(APIView):
    def get(self, request):
        obj = self.get_objects()
        serializer = ModelOutputSerializer(obj)

        return Response(serializer.data)

    def get_objects(self):
        model1 = Model1.objects.all()
        model2 = Model2.objects.all()

        obj = {'model1': model1, 'model2': model2}

        return obj

serializers.py serializers.py

class ModelOutputSerializer(serializers.Serializer):
    model1 = Model1Serializer(many=True)
    model2 = Model2Serializer(many=True)

    class Meta:
        fields = ('model1', 'model2')

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

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