我有一个父子表,
class Service( models.Model ):
id = models.CharField( primary_key=True, max_length=32 )
access_point = models.URLField( max_length=256 )
class Service2Service( models.Model ):
id = models.CharField( primary_key=True, max_length=32 )
parent_service = models.ForeignKey( Service, db_index=True, related_name="parent" )
child_service = models.ForeignKey( Service, db_index=True, related_name="child" )
我希望以html表格的形式显示内容,以便
parent 1
child 1.1
child 1.2
parent 2
child 2.1
...
所以我的观点给出了:
relations = Service2Service.objects.filter( blah )
并拥有regroup模板指令,但无法弄清楚如何编写重组以正确提供父级'标题'。任何想法?
答案 0 :(得分:1)
关键是尝试以Django的ORM喜欢的方式获得关系
首先,我重做了related_name,因此它是复数(小问题,但使代码更容易阅读)
class Service( models.Model ):
id = models.CharField( primary_key=True, max_length=32 )
access_point = models.URLField( max_length=256 )
class Service2Service( models.Model ):
id = models.CharField( primary_key=True, max_length=32 )
parent_service = models.ForeignKey( Service, db_index=True, related_name="parents_set" )
child_service = models.ForeignKey( Service, db_index=True, related_name="children_set" )
其次,在您的视图中获取一组父服务。
def my_view(request, ...
...
parent_services = Service.objects.filter( blah)
...
然后,一旦你进入模板,就可以编写一个嵌套的for循环:
{% for service in parent_services %}
<tr> ... {{service}} </tr>
{% for child_service in service.children_set.all %}
<tr> ... {{child_service}} </tr>
{% endfor %}
{% endfor %}
service.children_set.all命令遵循您的关系。