4

I have many rows in a queryset. Many of the rows share the same value in two fields.

I want to show the entire queryset in a table but I don't want to print those values which are the same multiple times.

My output would be something like

  mood, age, id
=============
  glad,  31, 1
      ,    , 2
      ,    , 3
      ,  32, 4
      ,    , 5
   sad,  31, 6
      ,    , 7
      ,  34, 8
      ,    , 9
      ,    , 10
 happy,  40, 11

I hope it makes sense. When multiple rows share the same value I don't want to print them again. I'm using the rowspan attribute to make the rows fill the number of rows which share the same values.

I know how to do with only one field:

{% regroup my_queryset by mood as mood_list %}
{% for mood in mood_list %}
    {% for node in mood.list %}
        <tr>
            {% if forloop.first %}
                <td rowspan="{{ mood.list|length }}">{{ mood.grouper }}</td>
            {% endif %}
            <td>{{ node.id }}</td>
        </tr>
    {% endfor %}
{% endfor %}

but I have no idea how to accomplish the same when both mood and age should 'fill multiple rows'. I guess there must be some good way as I've seen other sites doing the same with many fields (e.g. in business intelligence tools).

Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

3

Using the example from here and the parentloop hint from here, I have created the following code:

{% if my_queryset %}
    {% regroup my_queryset by mood as data_by_mood %}
    <table border="1">
        <thead>
            <caption>Data</caption>
            <tr><th>mood</th><th>age</th><th>id</th></tr>
        </thead>
        <tbody>
            {% for data0 in data_by_mood %}
                {% regroup data0.list by age as data0_by_age %}
                {% for data1 in data0_by_age %}
                    {% for data in data1.list %}
                        <tr>
                            {% if forloop.first %}
                                {% if forloop.parentloop.first %}
                                    <td rowspan="{{ data0.list|length }}">{{ data0.grouper }}</td>
                                {% endif %}
                                <td rowspan="{{ data1.list|length }}">{{ data1.grouper }}</td>
                            {% endif %}
                            <td>{{ data.id }}</td>
                        </tr>
                    {% endfor %}
                {% endfor %}
            {% endfor %}
        </tbody>
    </table>
{% endif %}

I hope it helps (it worked for me for a similar problem).

Community
  • 1
  • 1