tree structure of parent child relation in django templates

前端 未结 4 2048
借酒劲吻你
借酒劲吻你 2021-01-31 12:40

how do i implement the tree structure in django templates with out using django-mptt.

i have model.

class Person(TimeStampedModel):
    name  = models.Ch         


        
4条回答
  •  礼貌的吻别
    2021-01-31 13:32

    These are great answers but I consolidated a bit and put it on the actual model.

    class RecursiveThing(models.Model):
    
        name = models.CharField(max_length=32)
        parent = models.ForeignKey('self', related_name='children', blank=True, null=True)
    
        def as_tree(self):
            children = list(self.children.all())
            branch = bool(children)
            yield branch, self
            for child in children:
                for next in child.as_tree():
                    yield next
            yield branch, None
    

    And then in your template:

      {% for thing in things %} {% for branch, obj in thing.as_tree %} {% if obj %}
    • {{ obj.name }} {% if branch %}
        {% else %} {% endif %} {% else %} {% if branch %}
      {% endif %} {% endif %} {% endfor %} {% endfor %}

提交回复
热议问题