1

I have 2 models: Folder and Entity.

class Folder(models.Model):
    name = models.CharField(max_length=255, null=False, blank=False)
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name="child")

class Entity(models.Model):
    name = models.CharField(max_length=255, null=False, blank=False)
    folder = models.ForeignKey('Folder', on_delete=models.SET_NULL, null=True, blank=True, related_name="entities")

So a folder can have both child folders and entities. Now I want to send the data in a tree structure and I have written a serializer for it.

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

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

    def get_children(self, instance):
        child_folders = Folder.objects.filter(parent=instance).order_by("name")
        child_entities = Entity.objects.filter(folder=instance).order_by("name")
        all_children = []
        if child_folders or child_entities:
            child_folders_data = ListFolderSerializer(child_folders, many=True).data
            child_entities_data = ListEntitySerializer(child_entities, many=True).data
            all_children.extend(child_folders_data)
            all_children.extend(child_entities_data)
            return all_children
        else:
            return None 

class ListEntitySerializer(serializers.ModelSerializer):

    class Meta:
        model = Entity
        fields = ['id', 'name']

This is working fine but as the data keep on increasing the time to get this tree is increasing. So any optimized way to do this?

Akash Sharma
  • 129
  • 9
  • you have to use https://pypi.org/project/django-mptt/ if you want to send tree-like response – Tanveer Ahmad Jan 10 '23 at 12:10
  • @TanveerAhmad I don't want to change the model structure and this is just one use case of getting data in the tree but it is used in other places also. – Akash Sharma Jan 10 '23 at 13:17
  • https://stackoverflow.com/questions/44184751/django-rest-framework-list-route-and-queryset-on-tree-structure check out this link – Tanveer Ahmad Jan 10 '23 at 13:52

0 Answers0