Y
Y
Yzurgzd2020-10-18 15:17:49
Django
Yzurgzd, 2020-10-18 15:17:49

How to display nested categories?

There is a model

class Category(models.Model):
    name = models.CharField('Наименование', max_length=100)
    slug = models.SlugField(max_length=160, unique=True)
    parent = models.ForeignKey(
        'self', verbose_name='Родитель', on_delete=models.SET_NULL, blank=True, null=True, related_name='children'
    )


templatetags
@register.simple_tag()
def get_categories():
    return Category.objects.all()


I output, respectively, all categories are displayed together with their children. You can add in templatetags .filter(parent__isnull=True), but how then to display child categories?
{% get_categories as categories %}
{% for category in categories %}
<a>{ category.name }</a>
{% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-10-18
@Yzurgzd

Recursively. Google django-mptt and either use or steal the implementation from there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question