I'm using Django and Django-rest-framework, and I have the next Model and Serializer:
class Category(models.Model):
id_category = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
name = models.TextField(null=False)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id_category', 'name', 'parent')
Now, I want to make a query like Category.objects.filter(parent=None) that returns something like this:
[
{
"id_category": "UUID",
"name": "Father",
"childrens": [
{
"id_category": "UUID",
"name": "Son",
"childrens": [
{
"id_category": "UUID",
"name": "Grandson"
}
]
}
]
},
{
"id_category": "UUID",
"name": "Other"
}
]
As you see, a Category could have one father and many children. Need help to make this query, because I don't know how do that.