DRF - Сериализаторы = Я хочу получить json-данные для моих отношений "родитель-ребенок", как?
Я хочу создать TreeMenu в моем компоненте react, поэтому я использую это отношение родитель-ребенок -
model.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
serializers.py
class ParentCategorySerializer(ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(required=False, read_only=False, queryset=ProductCategory._default_manager.all())
sub_cats = SubCategorySerializer(many=True, required=False, read_only=False)
class Meta:
model = ProductCategory
fields = ('id', 'parent', 'name', 'desc', 'sub_cats')
получение моих данных в виде
[
{
"id":1,
"parent":null,
"name":"Electronics",
"desc":"All kinds of electronics items comes in this category",
"sub_cats": [
{
"id":2,
"name":"Mobiles",
"desc":"Category for Smartphones, Features-Phone, etc.",
"parent":1
},
{
"id":3,
"name":"Laptops",
"desc":"Category for different - 2 types of laptops.",
"parent":1
}
]
},
{
"id":2,
"parent":1,
"name":"Mobiles",
"desc":"Category for Smartphones, Features-Phone, etc.",
"sub_cats":[]
},
{
"id":3,
"parent":1,
"name":"Laptops",
"desc":"Category for different - 2 types of laptops.",
"sub_cats":[]
}
]
Как я могу сделать это лучше или что нужно сделать, чтобы сделать древовидное меню?