Sunday, 24 May 2015

Serializing Self Referential Model Recursively in Django REST Framework

Consider a Comment model with replies to it. Each comment can have multiple replies. Or in other words each reply may have a parent comment to which it is posted as a reply. Then how to serialize recursively? 

I can't use the following code - 

class CommentSerializer(serializers.ModelSerializer):
    replies = CommentSerializer(many=True)    
    
    class Meta:
        model = Comment
        fields = ('content', 'stamp_date', 'replies')

Because as the 1st line of the class is reached, till then CommentSerializer is not completely defined and this makes it as compile time error.

Whenever you find yourself in this soup, the solution is simple. Just have the following special recursive serializer defined in your serializers.py

class RecursiveField(serializers.Serializer):
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

And in your CommentSerializer simply use it - 

class CommentSerializer(serializers.ModelSerializer):
    replies = RecursiveField(many=True)

    class Meta:
        model = Comment
        fields = ('content', 'stamp_date', 'replies')

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.