[Answer]-Group by FK field

1👍

You can do this in two steps…

First get a queryset ordered how you want, but essentially a ‘flat’ list:

qs = Product.objects.order_by('website__name')

Then you could use something like itertools.groupby to output the sub-lists:

from itertools import groupby
from operator import attrgetter

keyfunc = attrgetter('website')
qs = Product.objects.order_by('website__name')
groups = []
uniquekeys = []
for website_name, products in groupby(qs, keyfunc):
    groups.append(list(products))
    uniquekeys.append(website_name)

Alternatively you could just pass the queryset into the template and use the regroup templatetag

{{% regroup qs by website as product_list %}

<ul>
{% for group in product_list %}
    <li>{{ group.grouper.name }}
    <ul>
        {% for product in group.list %}
          <li>{{ product.name }}: {{ product.website }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Leave a comment