Saturday, April 15, 2017

Django rest framework serializer with self-referential foreign key for comments

Django had default comments package sometime back (django.contrib.comments), since it's deprecated, there is external repo available for now.  It provides flat comments, so if you want threaded comments, you can use django-threadedcomments.

We are using django-rest-framework, and access the threaded comments via drf.

resources.py

class ObjectSerializer(serializers.ModelSerializer):

    comments = CommentsSerilizer(
        source='comments_set',
        many=True)

    class Meta:
        model = ObjectName
        fields = (
            "id",
            .....,
            "comments",
        )


serializers.py

from rest_framework import serializers
from .models import FluentComment

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

class CommentsSerilizer(serializers.ModelSerializer):
    children = RecursiveField(many=True)

    class Meta:
        model = FluentComment
        fields = (
            'comment',
            'url',
            'submit_date',
            'id',
            'children',
        )

Recursive Field is one way to get the self-referential objects via serializer, it handles parent-child relationship. Here is another way to do it -


class CommentsSerilizer(serializers.ModelSerializer):
    user = UserLightSerializer()

    class Meta:
        model = FluentComment
        fields = (
            'user',
            'comment',
            'submit_date',
            'id',
            'children',
        )

CommentsSerilizer._declared_fields[
     'children'] = CommentsSerilizer(many=True)


Above both options are fine, and it should do the magic. Good luck!

No comments:

Post a Comment