Search code examples
djangoparentforeign-key-relationship

Django and how to check if object has children


as a very much of a newbie in Django/python world I fail to find a way to check whether an object has children.

An example:

Class MyItems
        title = models.CharField(max_length=50)
        parent = models.ForeignKey('self',null=True, blank=True,related_name='subitems')

Then in my template:

{% for item in MyItems %}
<li> {{ item.title }} </li>
    {% if item **IS A PARENT OF CHILDREN** %}
        <p>This is what I want</p>
    {% endif %}
{% endfor %}  

I can see if an item has a parent no problem, but how to do it other way around, tell if an item is a parent to other item?

Thanks!


Solution

  • if you want a recursive parent child relationship between your objects you should look at using 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>
    

    talked about in the cookbook here: https://code.djangoproject.com/wiki/ModifiedPreorderTreeTraversal

    to understand how MPTT works at a data level, have a look at http://en.wikipedia.org/wiki/Nested_set_model

    The problem with the obvious solution, is that for each additional level children, another query is required - which gets extremely inefficient.

    # this is an additional query AND will not be recursive.
    {% if item.child_set.all.count > 0 %}