How to limit the number of fetched children in django-treenode

I have a comment Model, where a comment can be a root item or under another comment. I'm using REST API to get the full tree. Is it possible to limit its depth, so for example It will stop after 3 nodes from each root comment. I want to add a "more" feature instead of show the whole tree at once.

` class CommentSerializer(serializers.ModelSerializer): leaf_nodes = serializers.SerializerMethodField()

class Meta:
    model = Comment
    fields = [

def get_leaf_nodes(self, obj):
    return CommentSerializer(obj.get_children(), many=True).data


I tried looking at the documentation on GitHub but didn't find a solution.

I think that your problem is at DRF level. You should try to set depth parameter for your serializer. From the doc:

The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.

In the end I found out that I can use the obj.tn_level to check the depth level of the item. I used two Serializers. The first one is for the first round, where I limit the tn_level based on a const in settings. The second Serializer, uses a parameter I pass via context from the view to the Serializer, containing the level of the last leaf on the display and via another const from settings I fetch more nodes.

This way I show part of the nodes and via pressing "more" I load a few nodes each time.

Back to Top