Show a django relationship in a template
I have a django model as follows:
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)
In 开发者_C百科my view, I pass a certain person, and the relationships in which he/she is parent:
person = Person.objects.filter(name ='some name')
descendant_relationships = Relationship.objects.filter(parent = person)
An I want to show this person's descendants in a list in a template:
<ul>
{% for item in descendant_relationships%}
<li> {{item.child.name}} - {{item.description}} </li>
{% endfor %}
</ul>
But this template code will not show the children of children (i.e. grandchildren, great-grandchildren etc.). How can I get these lower level descendants to show up? I imagine recursion is necessary somewhere, but where?
First, set a related name for your relationship ForeignKeys:
parent = models.ForeignKey(Person, related_name='child_relationships')
child = models.ForeignKey(Person, related_name='parent_relationships')
Then add something like the following to your 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
Instead of a method to return the children, we can adapt this to return the relationships:
def get_descendant_relationships(self):
relationships = []
for child in self.child_relationships.all():
relationships += child.get_descendant_relationships()
return descendants
If you only need a one to many rel between parent and children, you can drop the extra table:
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
Examples:
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': {}}
精彩评论