[Fixed]-Django models: How do I access children from parent models?

1👍

You could try using django-mptt, which is designed for working with recursive models in Django.

Swap your model’s ForeignKey with TreeForeignKey, e.g:

class Category(MPTTModel, BaseTimeModel):
    name = models.CharField(max_length=NAME_FIELD, blank=False, null=False, unique=True, help_text=HELP_TEXT)
    level = models.IntegerField(blank=True, null=True)
    parent = models.TreeForeignKey("self", blank=True, null=True, related_name="children")
    details = models.CharField(max_length=DETAIL_FIELD, blank=True, null=True)

    class MPTTMeta:
        level_attr = 'level'

level_attr will contain the object’s level in the hierarchy, e.g. 0 for the top-most parent.

Taking an example from the documentation, your template would look something like this:

{% load mptt_tags %}

<ul class="root">
{% recursetree nodes %}
    <li>
        {{ node.name }}
        {% if not node.is_leaf_node %}
            <ul class="children">
                {{ children }}
            </ul>
        {% endif %}
    </li>
{% endrecursetree %}
</ul>

Refer to this tutorial for more information, their example is pretty similar to your own use case.

👤Chris

Leave a comment