[Django]-Django Rest Framework: Derived model serializer fields

3👍

The Corresponding Model would be as follows:

class DescriptionNode(BaseTreeNode):
    basetreenode = models.OneToOneField(BaseTreeNode, related_name="base_tree")
    description = models.CharField(_("Description"), max_length=200)

    class Meta:
        verbose_name = _("Description node")
        verbose_name_plural = _("Description nodes")

Serializer would be as follows:

from rest_framework_recursive.fields import RecursiveField

class BaseTreeNodeSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()
    subcategories = serializers.ListSerializer(source="children",child=RecursiveField())

    class Meta:
        model = BaseTreeNode
        fields = ('id', 'title', 'description', 'subcategories')

    def get_description(self, obj):
        return obj.base_tree.description #base_tree is related name of basetreenode field

Leave a comment