在模板中显示django关系

时间:2011-05-04 02:09:10

标签: django

我有一个django模型如下:

class Person(models.Model):
    name = models.CharField(max_length=255)

class Relationship(models.Model):
    parent = models.ForeignKey(Person)
    child = models.ForeignKey(Person)
    description = models.TextField(blank=True)

在我看来,我传递了某个人,以及他/她是父母的关系:

person = Person.objects.filter(name ='some name')
descendant_relationships = Relationship.objects.filter(parent = person)

我想在模板的列表中显示此人的后代:

<ul>
{% for item in descendant_relationships%}
    <li> {{item.child.name}}  -  {{item.description}} </li>
{% endfor %}
</ul>

但是这个模板代码不会显示孩子的孩子(即孙子,曾孙等)。我怎样才能让这些较低级别的后代出现?我想在某个地方需要递归,但在哪里?

2 个答案:

答案 0 :(得分:1)

首先,为您的关系设置相关名称ForeignKeys:

parent = models.ForeignKey(Person, related_name='child_relationships')
child = models.ForeignKey(Person, related_name='parent_relationships')

然后在Person models.py中添加如下内容:

def get_descendants(self):
    descendants = []
    children = [relationship.child for relationship in self.child_relationships.all()]
    for child in children:
        descendants += child.get_descendants()
    return descendants

我们可以调整它以返回关系,而不是返回子节点的方法:

def get_descendant_relationships(self):
    relationships = []
    for child in self.child_relationships.all():
        relationships += child.get_descendant_relationships()
    return descendants

答案 1 :(得分:0)

如果您只需要在父级和子级之间使用一对多的rel,则可以删除额外的表:

from django.db import models
class Person(models.Model):
    name = models.CharField(max_length=255)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='a_name')

    def genealogical_tree(self, type_of_members, generations):
        """
        @generations: the number of generations to be traversed in the tree(
            controls recursion)
        """
        formated_members = {}
        if generations:
            if type_of_members == 'parent':
                members = [self.parent]
            elif type_of_members == 'children':
                members = self._default_manager.filter(parent=self)
            for member in members:
                formated_members[member.name] = member.genealogical_tree(
                    type_of_members, generations-1)
        return formated_members

示例:

from models import Person
f=Person(name='f')
s=Person(name='s')
gs=Person(name='granson')
gs.save()
s.save()
f.save()

s.parent=f
s.save()
gs.parent=s
gs.save()

f.genealogical_tree('children',1)
>>> {u's': {}}
f.genealogical_tree('children', 2)
>>> {u's': {u'granson': {}}}
gs.genealogical_tree('parent', 2)
>>> {'s': {'f': {}}}
gs.genealogical_tree('parent', 1)
>>> {'s': {}}