Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Models in Django Rest Framework?

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.

like image 407
Coderaemon Avatar asked Feb 18 '16 15:02

Coderaemon


People also ask

How do I create multiple model instances with Django REST framework?

To create multiple model instances with the Python Django Rest Framework, we can create a serialize with many set to True . to call the super class' __init__ method with the many argument set to many . If it's True , then our serializer can accept multiple model instances.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is model serializer in Django REST framework?

ModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.


1 Answers

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',
    })
like image 178
bakkal Avatar answered Oct 27 '22 00:10

bakkal