1👍
✅
you can use ifchanged
qs = ShipClass.objects.order_by("Origin", "Classname")
{% for entry in qs %}
{% ifchanged entry.Origin %}
{{ entry.Origin }}
{% endifchanged %}
{{ entry.Classname }}
{% endfor %}
👤sax
0👍
in your view you can build a dictionary whose keys are the allegiance names and values are the list of classNames for that allegiance. To get the keys you can first access your model’s choices and then loop through each to make a filter query to get the corresponding className lists, something like:
starship_classes_by_allegiance = {}
for choice in ShipClass._meta.get_field('Origin').choices:
allegiance_id, allegiance_label = choice
starship_classes_by_allegiance[allegiance_label] = ShipClass.objects.filter(Origin=allegiance_id).values('ClassName').distinct()
then you can iterate over this dict in your template like:
{% for allegiance_label in starship_classes_by_allegiance %}
{{ allegiance_label }}
<ul>
{% for class_name in starship_classes_by_allegiance.allegiance_label %}
<li>{{ class_name }}</li>
{% endfor %}
</ul>
{% endfor %}
Source:stackexchange.com