我有 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/