Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize queryset in get method in Django Rest Framework?

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')
like image 549
Katsuya Obara Avatar asked Aug 28 '18 14:08

Katsuya Obara


1 Answers

You should be aware of these things,

  1. Since you are passing a QuerySet object, you must not provide the data argument.

  2. QuerySet is a list like object, so you should provide many=True while serialization.

  3. the 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

  1. Dealing with multiple objects in Serializer ---- many=True
  2. is_valid()
like image 81
JPG Avatar answered Sep 22 '22 18:09

JPG