Multiple Models in Django Rest Framework?

2019-03-18 12:22发布

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 only Cart object). Following models(unrelated) can be there.

class Ship_address(models.Model):
   ...

class Bill_address(models.Model):
   ...

class Cart(models.Model):
   ...

class Giftwrap(models.Model):
   ...

I tried using DjangoRestMultiplemodels, it works ok but has some limitations. Is there any in-built way ? Can't I append to the serializer that's created in the following view ?

from rest_framework.views import APIView

class CartView(APIView):
    """
    Returns the Details of the cart
    """

    def get(self, request, format=None, **kwargs):
        cart = get_cart(request)
        serializer = CartSerializer(cart)
        # Can't I append anything to serializer class like below ??
        # serializer.append(anotherserialzed_object) ??
        return Response(serializer.data)

I really like DRF. But this use-case(of sending multiple objects) makes me think if writing a plain old Django view will be better suited for such a requirement.

1条回答
做自己的国王
2楼-- · 2019-03-18 13:19

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',
    })
查看更多
登录 后发表回答