Django Polymorphic Serializer Object of type ListSerializer is not JSON serializable
I'm working on a django view to return a nested list inside another list of records, to do this I use a nested serializer. The thing is that nested serializer is a Polymorphic serializer that decomposes to many other serializers.
When I'm using a normal serializer instead of the polymorphic one the approach works fine, but when I use a polymorphic serializer it gives the following error
Object of type ListSerializer is not JSON serializable
Here is how I'm calling the first serializer in my view
return Response(serializers.FormEntriesHistorySerializer(forms,many=True,context={'device_id': kwargs.get('device_id')}).data)
And this is the parent serializer
class FormEntrySerializer(serializers.ModelSerializer):
#form = FormSerializer(read_only=True)
response_set = ResponsePolymorphicSerializer(many=True,read_only=True)
class Meta:
model = models.FormEntry
fields = '__all__'
def to_representation(self, instance):
response = super().to_representation(instance)
response["response_set"] = sorted(response["response_set"], key=lambda x: x["id"],reverse=True)
return response
def validate(self, attrs):
print("Validation in on going")
return attrs
The error is triggered by the ResponsePolymorphicSerializer, as I said this approach works fine if I use a normal serializer instead. But in this case I need to do it with the polymorphic.
Here's my polymorphic serializer's definition
class ResponsePolymorphicSerializer(PolymorphicSerializer):
model_serializer_mapping = {
models.FreeTextResponse: FreeTextResponseSerializer,
models.ShortTextResponse: ShortTextResponseSerializer,
I'd gladly appreciate some guidance on this. Thanks.