Multiple Models in Django Rest Framework?

前端 未结 1 2017
轮回少年
轮回少年 2021-02-01 19:17

I am using Django Rest framework. I want to serialize multiple models and send as response. Currently I can send only one model per view(like CartView below sends o

相关标签:
1条回答
  • 2021-02-01 19:36

    You can customize it, and it wouldn't be too weird, because this is an APIView (as opposed to a ModelViewSet from which a human being would expect the GET to return a single model) e.g. you can return several objects from different models in your GET response

    def get(self, request, format=None, **kwargs):
        cart = get_cart(request)
        cart_serializer = CartSerializer(cart)
        another_serializer = AnotherSerializer(another_object)
    
        return Response({
            'cart': cart_serializer.data,
            'another': another_serializer.data,
            'yet_another_field': 'yet another value',
        })
    
    0 讨论(0)
提交回复
热议问题