首页 \ 问答 \ Django模板中具有相同位置的编号列表?(A numbered list with some equal positions in a Django template?)

Django模板中具有相同位置的编号列表?(A numbered list with some equal positions in a Django template?)

在我的Django模板中,我有一个从QuerySet构建的图表,按score降序排序,类似这样(省略任何HTML标记):

{% for player in players %}
    {{ forloop.counter }}. {{ player.name }} ({{ player.score }})
{% endfor %}

但是,如果相邻的球员得分相等,我希望他们的位置相同,即:

1.  Bob    (100)
2=. Thelma  (95)
2=. Terry   (95)
4.  Audrey  (90)

我是否认为使用Django的标准模板标签(我不使用Jinja)无法做到这一点? 最好的方法是在视图中(或者它来自何处)遍历QuerySet并在那里计算这些位置,在它们到达模板之前将它们添加到每个项目中?


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?


原文:https://stackoverflow.com/questions/39981174
更新时间:2021-04-10 13:04

最满意答案

这似乎更像是在视图中处理的事情:

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})

模板:

{% for player in players %}
    {{ player.position }}. {{ player.name }} ({{ player.score }})
{% endfor %}

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 %}

相关问答

更多