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?
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)
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With