亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python/Django遞歸模型到樹結構字典

Python/Django遞歸模型到樹結構字典

Cats萌萌 2023-02-22 15:23:21
我有一個 Django 模型class Category(models.Model):    parent = models.ForeignKey('Category', null=False, blank=False)    category_name = models.CharField(max_length=55,null=False, blank=False)    status = model.BooleanField(default=True)我想創建返回樹結構字典的遞歸。例如[    {        'category_name': 'vehical',        'id': 1,        'children' : [            {                'category_name': 'cars',                'id': 11,                'children': [                    {                        'category_name': 'sport cars',                        'id': 20                    }                               ]                           }               ]    }]>>> category = Category.objects.all()>>> get_tree(category)
查看完整描述

1 回答

?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

我認為您需要將您的ForeignKey關系更改為self, 以引用自身。此外,為了簡化實現,讓我們添加related_name='children'( doc ) 并將其設為 nullable( null=True) 以將其表示為根節點。


class Category(models.Model):

    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

    category_name = models.CharField(max_length=55,null=False, blank=False)

    status = models.BooleanField(default=True)

然后我們可以做如下實現:


from django.forms.models import model_to_dict


def get_tree(category):

    tree = model_to_dict(category, fields=['category_name', 'status', 'id'])

    if category.children.all().exists():

       children = list()

       for child in category.children.all():

          children.append(get_tree(child))

       tree['children'] = children

    return tree


final_tree = list()

for category in Category.objects.filter(parent__isnull=True):

    final_tree.append(get_tree(category))

print(final_tree)


查看完整回答
反對 回復 2023-02-22
  • 1 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號