I have a sample table below with a parent-child relationship.
| id | parent |
|---|---|
| 1 | null |
| 2 | 1 |
| 3 | 2 |
| 4 | null |
I have to represent this in the UI as a tree structure. What is or are the best approaches to this? Do I fetch the data as flat from the API and restructure it as tree hierarchy at the front-end.
[
{
"id": 1,
"parent": null,
},
{
"id": 2,
"parent": 1,
},
{
"id": 3,
"parent": 2,
},
{
"id": 4,
"parent": null,
}
]
OR
The API should per-structure the response as a tree such that the UI simply consumes it.
[
{
"id": 1,
"parent": null,
"children": [
{
"id": 2,
"parent": 1,
"children": [
{
"id": 3,
"parent": 2,
"children": []
}
]
}
]
},
{
"id": 4,
"parent": null,
"children": []
}
]
If I have to use something like the second approach, what is the most efficient way to do this such that there will not be duplicate entries.
I'm using djangorestframework and react.
you can custom logic in serializer using serializers.SerializerMethodField()
Model
Serializer
The implementation aims to showcase the use of context, allowing for flexibility according to your use case.
view
add filter
parent=Noneinto query setAnyway if you set '
queryset = FolderModel.objects.all().filter(parent=None)' in view there are no chance to hit 'Recursive Exceeded'. So you can just return serializer directly