a.powell
a.powell

Reputation: 1722

Django Template and Bootstrap Tables

I have a django queryset that looks something like this

Group Label Name
A     1     Jack
A     2     Ryan
B     2     Alice
C     1     Sam
B     1     Mark
...

Basically, what I am attempting to do in my html, is create 6 small tables (2 rows of 3 tables). However, I want the first table to be Group A sorted by Label #, the second to be Group B sorted by Label #, etc.

I could bite the bullet and do 6 different django querysets, but this seems inefficient.

My initial thought was to have some counter in the django template to keep track of whether or not to start a new row. However, I am not sure if there is a way to filter & sort in the django template instead of the view.

Thanks for any help.

Upvotes: 0

Views: 4326

Answers (1)

Jonah Bishop
Jonah Bishop

Reputation: 12571

Here's what I would do:

  1. Order the queryset the way you want (sorted by group, then by label) by using the order_by operation.
  2. In your template, use the ifchanged conditional to test to see when you have a different group. In that case, you output the table tags as necessary.

Example of item 2 above:

{% for object in queryset %}
  {% ifchanged obj.group %}
  <table>
  {% endifchanged %}
    <tr>
      <td>{{ obj.label }}</td>
      <td>{{ obj.name }}</td>
    </tr>
  {% ifchanged obj.group %}
  </table>
  {% endifchanged %}
{% endfor %}

Upvotes: 1

Related Questions