Multiple Models in Django Rest Framework?

17,353

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',
    })
Share:
17,353

Related videos on Youtube

Coderaemon
Author by

Coderaemon

Cartoon turned Engineer.

Updated on September 15, 2022

Comments

  • Coderaemon
    Coderaemon over 1 year

    I am using Django Rest framework. I want to serialize multiple models and send them as a 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 wonder if writing a plain-old Django view will be better suited for such a requirement.

  • latsha
    latsha over 7 years
    I would be so thankful if you will extend your answer with how to make it work with pagination.