Multiple Models in Django Rest Framework?

前端 未结 1 2016
轮回少年
轮回少年 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)
提交回复
热议问题