Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django category list (parent child)

Tags:

django

I have a category list with parent - child relationship:

class Categories(models.Model):
  cat_name = models.Charfield()
  cat_parent = models.ForeignKey('self')

So i want to list them as such:

Category 1
  Sub category 1
  Sub category 2
  Sub category 3
Category 2
  Sub category 4
  Sub category 5

etc...

What's the best way to do this?

like image 908
R0b0tn1k Avatar asked Jan 04 '12 17:01

R0b0tn1k


2 Answers

depending on your actual use case, this may be overkill, but have a look at django-mptt, (Modified Preorder Tree Traversal), a library which simplifies dealing with hierarchical data using a sql database (and, in this case, django)

like image 178
second Avatar answered Sep 30 '22 16:09

second


You can do this so

categories ={}

map(lambda c: categories.setdefault(c.cat_parent, []).append(c),\
    Categories.objects.filter(cat_parent__isnull=False)\
        .select_related('cat_parent'))

And you will get categories dict like

{
    Category 1 : [Sub category 1, Sub category 2, Sub category 3],
    Category 2 : [Sub category 4, Sub category 5]
}

Then in your template

{% for category, sub_categories in categories.items %}
    {{ category.name }}
    {% for sub_category in sub_categories %}
        {{ sub_category }}
    {% endfor %}
{% endfor %}
like image 20
Alexey Savanovich Avatar answered Sep 30 '22 17:09

Alexey Savanovich