'DRF Serailze Parent-Child Relation models
I have Parent-Children Relation Table in Model which is as follows:
models.py
class ProductCategory(models.Model):
parent = models.ForeignKey(to='ProductCategory', blank=True, null=True, related_name="sub_cats", on_delete=models.CASCADE)
name = models.CharField(max_length=30, blank=False, null=False)
desc = models.TextField(blank=True, null=True, db_column='description')
def __str__(self):
return self.name
Using this data I want to make a tree in react component where a user see how many types of categories a product has.
right now getting this
[
{
"id": 1,
"parent": null,
"name": "Electronics",
"desc": "All kinds of electronics items comes in this category",
"sub_cats": [
{
"id": 2,
"parent": 1,
"name": "Mobiles",
"desc": "Category for Smartphones, Features-Phone, etc.",
"sub_cats": [3]
}
]
},
{
"id": 2,
"parent": 1,
"name": "Mobiles",
"desc": "Category for Smartphones, Features-Phone, etc.",
"sub_cats": [
{
"id": 3,
"parent": 2,
"name": "X-Mobile",
"desc": "All Smartphones of X-Mobile",
"sub_cats": []
}
]
},
{
"id": 3,
"parent": 2,
"name": "X-Mobile",
"desc": "All Smartphones of X-Mobile",
"sub_cats": []
}
]
or any other idea for making tree
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
