我正在使用Django和Django-rest-framework,我有下一个Model和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')
现在,我想创建一个类似Category.objects.filter(parent=None)
的查询,返回如下内容:
[
{
"id_category": "UUID",
"name": "Father",
"childrens": [
{
"id_category": "UUID",
"name": "Son",
"childrens": [
{
"id_category": "UUID",
"name": "Grandson"
}
]
}
]
},
{
"id_category": "UUID",
"name": "Other"
}
]
如你所见,一个类别可能有一个父亲和许多孩子。需要帮助才能进行此查询,因为我不知道该怎么做。
答案 0 :(得分:1)
您可以为子类别编写其他序列化程序:
class ChildrenSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id_category', 'name', 'parent')
class CategorySerializer(serializers.ModelSerializer):
children = ChildrenSerializer(many=True)
class Meta:
model = Category
fields = ('id_category', 'name', 'parent', 'children')
你could also show nested models with depth option:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
depth = 1
fields = ('id_category', 'name', 'parent', 'children')