Reputation: 14594
In my Django template I have a chart built from a QuerySet, ordered descending by score
, something like this (omitting any HTML tags):
{% for player in players %}
{{ forloop.counter }}. {{ player.name }} ({{ player.score }})
{% endfor %}
However, if adjacent players have equal scores, I want their positions to be the same, i.e.:
1. Bob (100)
2=. Thelma (95)
2=. Terry (95)
4. Audrey (90)
Am I right in thinking there's no way to do this using Django's standard template tags (I'm not using Jinja)? Would the best way be to loop through the QuerySet in the view (or wherever it comes from) and calculate these positions there, adding them to each item before they get to the template?
Upvotes: 0
Views: 748
Reputation: 844
this seems more like something to be handled in the view:
players = your_queryset
ordered_players = []
counter = 1
previous_player = PlayerModel.objects.none()
for player in players.order_by("score"):
if player.score == previous_player.score:
position = previous_player.position
else:
position = counter
ordered_players.append({
"position": position,
"name": player.name,
"score": player.score
})
previous_player = player
counter += 1
return render(request, "template.html", {"players": ordered_players})
template:
{% for player in players %}
{{ player.position }}. {{ player.name }} ({{ player.score }})
{% endfor %}
Upvotes: 1