django - 指定 Django 相关模型排序顺序

标签 django django-models django-views django-queryset

我有 Django 模型,它们是项目列表,我希望每个列表上的项目都有单独的排序顺序。也许列表 1 将按名称排序行项目,列表 2 按日期排序,列表 3 按优先级排序。

模型看起来或多或少像这样:

class ListItem(models.Model):
    priority = models.IntegerField(choices=PRIORITY_CHOICES)
    name = models.CharField(max_length=240)
    due_date = models.DateTimeField(null=True, blank=True)
    list = models.ForeignKey(List)

现在我在我的 View 中使用此查询:

lists = List.objects.filter(user=request.user)
return render_to_response('showlists.html', {'lists': lists })

我读过的例子暗示我可以做这样的事情:

lists = List.objects.filter(user=request.user).select_related().order_by("items.name")

假设这有效,它会给我每批项目具有相同排序顺序的列表集合。我将如何对每个列表的相关项目进行不同的排序?

最佳答案

跨相关模型排序的语法与 filter 的双下划线格式相同,因此您可以执行以下操作:

List.objects.filter(user=request.user).select_related().order_by("listitems__name")

您应该能够在 order_by 调用中以相同的方式使用不同的字段。

关于django - 指定 Django 相关模型排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/967781/

相关文章:

javascript - django找不到静态文件

django - Heroku Piggyback SSL 的安全性如何

python - Django 表单未以 HTML 呈现

python - Django modelform 外键更新

Django "The submitted file is empty"

django - 将未绑定(bind)的表单转换为绑定(bind)的表单?

python - 使用 django 模型有效获取数据

python - Django 请求查找以前的推荐人

python - 如何在 python - Django 中从数据库获取列表到 html?

python - 在 Django 中创建模型