Django REST framework serializer without a model

DjangoDjango Rest-FrameworkDjango Serializer

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarid El NasireView Question on Stackoverflow
Solution 1 - DjangocodeadictView Answer on Stackoverflow