[Fixed]-How to serialize queryset in get method in Django Rest Framework?

37๐Ÿ‘

โœ…

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()
๐Ÿ‘คJPG

7๐Ÿ‘

As far as I can see you need to provide serializer class with many=True.
As for docs:

To serialize a queryset or list of objects instead of a single object
instance, you should pass the many=True flag when instantiating the
serializer. You can then pass a queryset or list of objects to be
serialized.

http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects

So the line that raises error should look this way

serializer = summarySerializer(queryset, many=True)
๐Ÿ‘คwiaterb

Leave a comment