Displaying Categories / Subcategories (Tango with Django Example)

575 views
Skip to first unread message

Michael Smith

unread,
May 10, 2017, 1:40:26 PM5/10/17
to Django users
I'm following the latest Tango book and was experimenting with different ways of looping through categories and subcategories to create a list.  I have a 'Category' and 'Page' model, where Page has a foreign key to Category's ID.  To display a list with sub-bullets I simply passed all categories and pages to a template and then looped through Page:

<ul>
  {% if cats %}
    {% for c in cats %}
      {% if c == act_cat %}
      <strong><li><a href="{% url 'show_category' c.slug %}">{{ c.name }}</a></li>
      </strong>
      {% else %}
      <li><a href="{% url 'show_category' c.slug %}">{{ c.name }}</a>
      {% endif %}
        {% for p in pages %}
          {% if p.category_id == c.pk %}
            <ul><li><a href="{{ p.url }} ">{{ p.title }}</li></ul>
          {% endif %}
        {% endfor %}
    {% endfor %}
  {% else %}
    <li><strong>There are no categories present.</strong></li>
  {% endif %}
</ul>

Is this considered the best way to do such a thing?

jorr...@gmail.com

unread,
May 12, 2017, 7:05:21 AM5/12/17
to Django users
You can look into the {% regroup %} template tag. It will do what you are trying to do more elegantly.

carlos

unread,
May 12, 2017, 12:04:01 PM5/12/17
to django...@googlegroups.com
{% regroup %} is elegantly or more optimized???

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/96558026-ac69-4c7c-bb98-cee43dddee82%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
att.
Carlos Rocha

jorr...@gmail.com

unread,
May 12, 2017, 12:14:42 PM5/12/17
to Django users
Both, actually. The OP is looping through his cats and pages querysets multiple times unnecessarily. That can get very inefficient as those database tables get bigger.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.



--
att.
Carlos Rocha
Reply all
Reply to author
Forward
0 new messages