104

I'm working on a couple endpoints which aggregate data. One of the endpoints will for example return an array of objects, each object corresponding with a day, and it'll have the number of comments, likes and photos that specific user posted. This object has a predefined/set schema, but we do not store it in the database, so it doesn't have a model.

Is there a way I can still use Django serializers for these objects without having a model?

Farid El Nasire
  • 1,753
  • 4
  • 15
  • 17

1 Answers1

202

You can create a serializer that inherits from serializers.Serializer and pass your data as the first parameter like:

serializers.py

from rest_framework import serializers

class YourSerializer(serializers.Serializer):
   """Your data serializer, define your fields here."""
   comments = serializers.IntegerField()
   likes = serializers.IntegerField()

views.py

from rest_framework import views
from rest_framework.response import Response

from .serializers import YourSerializer

class YourView(views.APIView):

    def get(self, request):
        yourdata= [{"likes": 10, "comments": 0}, {"likes": 4, "comments": 23}]
        results = YourSerializer(yourdata, many=True).data
        return Response(results)
codeadict
  • 2,643
  • 1
  • 15
  • 11
  • 14
    useful answer! Docs here: http://www.django-rest-framework.org/api-guide/serializers/ – Chris Mar 15 '18 at 13:57
  • 3
    In this case is possible to add calculated field to YourSerializer? – Shrikanth Kalluraya Jan 30 '21 at 01:09
  • This worked perfectly! I wanted to expose a list of tuples with some constant values to an API endpoint. I had to convert them into a list of objects, but that was all the change I needed in the view class. – NurShomik Jan 18 '22 at 02:01
  • I am getting `AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.` by referring this answer. Do you have any pointers? – Harsha Biyani Jun 06 '22 at 06:42
  • `router.register(r'my-model/', MyModelView, basename='MyModel')` add basename like this – Harsha Biyani Jun 06 '22 at 10:40