作为Django/python世界中的一个新手,我找不到一种方法来检查一个对象是否有孩子。
举个例子:
Class MyItems
title = models.CharField(max_length=50)
parent = models.ForeignKey('self',null=True, blank=True,related_name='subitems')然后在我的模板中:
{% for item in MyItems %}
<li> {{ item.title }} </li>
{% if item **IS A PARENT OF CHILDREN** %}
<p>This is what I want</p>
{% endif %}
{% endfor %} 我可以看到如果一个项目有一个父项目没有问题,但如何做反过来,判断一个项目是否是其他项目的父项目?
谢谢!
发布于 2012-09-05 23:20:58
如果您想要对象之间的递归父子关系,则应考虑使用MPTT
http://django-mptt.github.com/django-mptt/
<ul class="root">
{% recursetree nodes %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>在这里的食谱中谈到:https://code.djangoproject.com/wiki/ModifiedPreorderTreeTraversal
要了解MPTT在数据级别上的工作原理,请看一下http://en.wikipedia.org/wiki/Nested_set_model
显而易见的解决方案的问题是,对于每个额外级别的子级,都需要另一个查询-这变得非常低效。
# this is an additional query AND will not be recursive.
{% if item.child_set.all.count > 0 %} 发布于 2012-09-29 22:38:27
如果我没理解错的话,应该是这样简单的:
{% if item.subitems.exists %}https://stackoverflow.com/questions/12284630
复制相似问题