Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework serializer without a model

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?

like image 503
Farid El Nasire Avatar asked Aug 06 '17 14:08

Farid El Nasire


People also ask

Can we use model Viewsets without model serializer?

You could create a View that extends APIView and return directly the response on get method without Serializer. There are ModelSerializer, ViewSet which are more related to Models, but everything is not implemented on them, they extend other classes, so you could go to the parent class and extend it.

Do we need Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is the difference between serializer and model serializer?

The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .

How do you make a serializer optional in Django?

Set to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True .


1 Answers

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) 
like image 62
codeadict Avatar answered Sep 18 '22 11:09

codeadict