【问题标题】:Django ORM - sort by name and scoreDjango ORM - 按名称和分数排序
【发布时间】:2023-04-11 00:01:02
【问题描述】:

我有这两个模型:

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

我想按以下顺序排列所有分数:

  1. 游戏名称
  2. 游戏内得分

所以,我想要的结果是:

游戏 A

  • 100.000
  • 90.000
  • 80.000

游戏 B

  • 50.000

  • 40.000

  • 30.000

游戏 C

  • 200.000

  • 190.000

  • 180.000

我希望你能明白。谢谢!

【问题讨论】:

  • 模型是否通过外键关联?添加完整模型
  • @gdef_ 抱歉,我忘记了 ForeignKey。我已经添加了外键。有很多不相关的属性我没有发布。我现在看不出它们有什么用处。

标签: django django-orm


【解决方案1】:

ORM 中的简单order_by 与内置模板标签regroup 相结合,将完全符合您的要求。 example in the Django docs for regroup 几乎正是您想要做的。

我假设您的 Score 模型具有 ForeignKeyGroup 模型。

在你看来,你会做这样的事情:

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

【讨论】:

  • 您应该添加select_related 以确保完整性。所以从一开始就正确完成。
  • @GregKaleka 就像一个魅力。非常感谢!
猜你喜欢
  • 2019-10-14
  • 2018-05-26
  • 2017-11-23
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2021-09-13
  • 2016-10-10
  • 2013-08-22
相关资源
最近更新 更多