You need to enable JavaScript to run this app. Django中如何按Episode模型的number字段对关联剧集实现降序排序?
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何按Episode模型的number字段对关联剧集实现降序排序?

按number字段实现模型对象降序排序的实现方案

针对当前视图代码的直接修改

在SeasonDetailView的get_context_data方法中查询剧集数据时,对返回的查询集追加排序规则即可。Django ORM 中,字段名前添加 - 前缀即代表按照该字段执行降序排序。

修改前后代码对比

  • 原有查询代码:
    context["episodes"] = Episode.objects.filter(season=self.object)
  • 追加number字段降序排序后的代码:
    context["episodes"] = Episode.objects.filter(season=self.object).order_by("-number")

可复用的全局排序配置

如果希望所有对Episode模型的查询默认都按number字段降序返回,无需在每个视图中重复编写排序逻辑,可以直接在Episode模型中配置元选项默认排序:
在现有Episode类定义末尾追加内部Meta类,完整类定义参考如下:

class Episode(models.Model):
    # 原有字段定义保持不变
    season = models.ForeignKey(CartoonSeason, on_delete=models.CASCADE)
    number = models.IntegerField()
    cover  = models.URLField(max_length=300, blank=True, null=True)
    name = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=False)
    link = models.URLField(max_length=300, blank=True, null=True)
    published = models.DateField(auto_now_add=True, blank=True, null=True)

    class Meta:
        # 配置默认排序规则:按number字段降序
        ordering = ["-number"]

配置完成后,所有没有主动指定排序规则的Episode查询,都会自动按照number字段从大到小的顺序返回结果。

注意:如果在某个具体查询中手动指定了order_by规则,会覆盖模型Meta中配置的默认排序。


内容的提问来源于stack exchange,提问作者Flamiooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.07 05:45:05