2017-04-19 83 views
0

我使用Django Django的和靜止的框架,和我有未來型號和序列化:Django的嵌套關係數據

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" 
    } 
] 

正如你所看到的,一個Category可以有一個父親和許多孩子。需要幫助來做這個查詢,因爲我不知道該怎麼做。

回答

0

你可以寫子類別的附加串行:

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')