在Django模板中以多种模型递归显示MPTT树

时间:2019-01-31 18:22:29

标签: python django django-mptt

所以,我使用的Django MPTT建立我的数据库中的树形结构,我会再像在递归树,并在HTML树型结构显示的对象。但是,每当我在模板中使用{%recursetree Architecture%}调用时,它只会显示Architecture对象。我希望能找到一种方法,通过显示每个节点的树遍历下来。任何帮助表示赞赏。

models.py

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey


class Architecture(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='Children')

    class MPTTMeta:
        order_insertion_by = ['name']


class Vehicle(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    mass = models.IntegerField()
    parent = TreeForeignKey('Architecture', on_delete=models.CASCADE, null=True, blank=True, related_name='Systems')

    class MPTTMeta:
        order_insertion_by = ['name']


class System (MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    mass = models.IntegerField()
    parent = TreeForeignKey('Vehicle', on_delete=models.CASCADE, null=True, blank=True, related_name='SubSystems')

    class MPTTMeta:
        order_insertion_by = ['name']


class SubSystem(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    mass = models.IntegerField()
    parent = TreeForeignKey('System', on_delete=models.CASCADE, null=True, blank=True)

    class MPTTMeta:
        order_insertion_by = ['name']


class Mission(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('Architecture', on_delete=models.CASCADE, null=True, blank=True, related_name='Events')

    class MPTTMeta:
        order_insertion_by = ['name']


class Event(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('Mission', on_delete=models.CASCADE, null=True, blank=True)

    class MPTTMeta:
        order_insertion_by = ['name']

views.py

from django.shortcuts import render
from dyreqt_UX.models import Architecture, SubSystem

from django.http import HttpResponse


def show_tree(request):
    return render(request, 'dyreqt_UX/tree.html', {'Architecture': Architecture.objects.all})

tree.html

{% load mptt_tags %}
 <ul class="root">
 {% recursetree Architecture %}
     <li>
         {{ node.name }}
         {% if not node.is_leaf_node %}
             <ul class="Children">
                 {{ Children }}
             </ul>
         {% endif %}
     </li>
 {% endrecursetree %}

0 个答案:

没有答案