'Serialize custom data in DRF
I have two types of static data and don't need any models because I don't want to save those data in the database. The data are generated from a class RandomObjectGenerator.
- Data 1 is a string whose length could be up to
2,097,152 - Date 2 is a JSON data whose size could be up to 4 like
{'a':1, 'b':2, 'c':3, 'd':4}
views.py
from django.shortcuts import render
from rest_framework import views
from rest_framework.response import Response
from .generate import RandomObjectGenerator
from .serializers import ObjectSerializers
import json
# Create your views here.
class ApiView(views.APIView):
def get(self, request):
randomObject=RandomObjectGenerator().get_random_objects()
randomObjectCount=RandomObjectGenerator().get_random_object_count()
objectSerialize=ObjectSerializers(data={'randData':randomObject,'randCount': json.dumps(randomObjectCount)})
if objectSerialize.is_valid():
objectSerialize.save()
return Response(objectSerialize.data)
else:
return Response(objectSerialize.errors)
serializers.py
from rest_framework import serializers
class ObjectSerializers(serializers.Serializer):
randData=serializers.CharField()
randCount=serializers.IntegerField()
I am getting two types of errors here. If I use serializers.IntegerField() then I am getting the "A valid integer is required." error then if I try to use serializers.CharField() then it's showing create() must be implemented.
I got stuck for while and couldn't get any idea how i fixed it.
Solution 1:[1]
create() need to be implemented on any serializer you call .save() because calling create is what save does.
So the question really is, why are you calling .save() if you have no intention of saving this to a database? what are you conceptually saving here?
Removing the row with save() from the view should solve your issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | krs |
