Django REST framework serializer without model

I am working on several endpoints that combine data. One of the endpoints, for example, will return an array of objects, each object corresponding to the day, and will have the number of comments, likes and photos that the user posted. This object has a predefined / installed schema, but we do not store it in the database, so it does not have a model.

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

+5
source share
1 answer

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) 
+9
source

Source: https://habr.com/ru/post/1270626/


All Articles