Yuval Adam
Yuval Adam

Reputation: 165202

Grouping models by field in Django

Consider a simple Django model:

class MyModel(models.Model):
    a = models.CharField()
    b = models.CharField()

And a query that fetches them in a view:

objs = MyModel.objects.all()

Now here's the tricky part, the template should render objects that have the same a field together. So if I have three objects:

{a:'1', b:'5'}, {a:'1', b:'8'}, {a:'2', b:'4'}

they should render like this in the output:

Basically, I need to group objects by their a field and render those groups differently than objects that have unique a fields.

How should I go about grouping these objects and displaying them differently?

Upvotes: 1

Views: 247

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

Order them by the a field, then do the grouping in the template with the regroup tag.

Code example:

{% regroup objs by a as objs_list %}
<ul>
  {% for a in objs_list %}
    {% if a.list|length == 1 %}
    <li>{{ a.grouper }}, {{ a.list.0.b }}</li>
    {% else %}
    <li>{{ a.grouper }}
      <ul>
      {% for obj in a.list %}
        <li>{{ obj.b }}</li>
      {% endfor %}
      </ul>
     {% endif %}
   </li>
   {% endfor %}      
</ul>

Upvotes: 3

Related Questions