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.
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.
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.
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.
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',
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With