我有两个模型:
class Game(models.Model):
name = models.CharField(max_length=255)
...
class Score(models.Model):
score = models.BigIntegerField()
game = ForeignKey(Game, blank=True, null=True, on_delete=models.PROTECT)
...
我想按以下方式对所有分数进行排序:
- 游戏名称
- 游戏中得分
所以,我想要的结果是:
游戏 A
- 100.000
- 90,000
- 80,000
游戏B
50,000
40,000
30,000
游戏C
200,000
190,000
180,000
我希望你明白这个想法。谢谢!
ORM中的简单order_by
,结合内置的模板标签regroup
将完全满足您的需求。Django 文档中regroup
的例子几乎正是你想要做的。
我假设您的Score
模型与Group
模型有ForeignKey
。
在您看来,您将执行以下操作:
# views.py
class ScoreListView(ListView):
model = Score
queryset = Score.objects.select_related('game')
.order_by('game__name', '-score')
# score_list.html
<!-- other content -->
{% regroup scores by game as game_list %}
{% for game, game_scores in game_list %}
<h2>{{ game }}</h2>
<ul>
{% for score in game_scores %}
<li>{{ score.score }}</li>
{% endfor %}
</ul>
{% endfor %}