I am trying to implement calculation logic in APIView class following this page.
However, I got below error because I tried to serialize queryset, not dictionary as demonstrated in the page.
Does anyone know how I can pass queryset to serializer as argument? If not, are there any way to convert into format which can be serialized by serializer?
{
"non_field_errors": [
"Invalid data. Expected a dictionary, but got QuerySet."
]
}
views.py
class envelopeData(APIView):
def get(self,request,pk):
#pk=self.kwargs['pk']
#print (pk)
glass_json=self.get_serialized(pk,"glass")
print (glass_json)
def get_serialized(self,pk,keyword):
queryset = summary.objects.filter(html__pk=pk).filter(keyword=keyword)
serializer = summarySerializer(data=queryset) <=get error here
serializer.is_valid(raise_exception=True)
data=serializer.validated_data
return data["json"]
serializer.py
class strToJson(serializers.CharField):
def to_representation(self,value):
x=JSON.loads(value)
return x
class summarySerializer(serializers.ModelSerializer):
project=serializers.CharField(read_only=True,source="html.project")
version = serializers.CharField(read_only=True, source="html.version")
pk = serializers.IntegerField(read_only=True, source="html.pk")
json = strToJson()
#json=serializers.JSONField(binary=True)
class Meta:
model=summary
fields=('pk','project','version','json')
You should be aware of these things,
QuerySet
object, you must not provide the data
argument.QuerySet
is a list
like object, so you should provide many=True
while serialization.is_valid()
method only is applicable only if you pass a dictionary to the data
argument, which is not here.So, change you get_serialized()
method as,
def get_serialized(self, pk, keyword):
queryset = summary.objects.filter(html__pk=pk).filter(keyword=keyword)
serializer = summarySerializer(queryset, many=True)
data = serializer.data
return data["json"]
References
many=True
is_valid()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With