How to serializer my children model objects properly?

  django, django-rest-framework, python

Here I am trying to return the children objects serialized data like this but this is not working.

I got this error.

 raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Type is not JSON serializable

How to solve this issue ?

model

class Type(models.Model):
    name = models.CharField(max_length=200, unique=True)
    parent = models.ForeignKey(
        'self', on_delete=models.PROTECT, null=True, blank=True)

serializer

class ListTypeSerializer(serializers.ModelSerializer):
    
    children = serializers.SerializerMethodField()

    class Meta:
        model = Type
        fields = ['name', 'children']

    # for some reason I can not do `return obj.type_set.values('name')`
    # since I have so many customized variable names.
    # I am displaying only name here in question.

    def get_children(self, obj):
        return ListTypeSerializer(obj.type_set.all(), many=True, context={'request': self.context['request']}).data

Source: Python Questions

LEAVE A COMMENT