我目前正在使用django-mptt
Django软件包,我正在尝试针对过滤器运行.order_by()
但它无法正常工作 - 更具体地说,无论{{1}哪个顺序都保持不变}} 我用。这是我目前的代码:
views.py
order_by()
_Article-modal.html
class ArticleModalView(View):
def get(self, request):
article_id = request.GET['article_id']
article = get_object_or_404(Article, id=article_id)
article_comments_recent = ArticleComment.objects.filter(article=article).order_by('-created')
return render(request, '_includes/_article-modal.html', {'article': article, 'article_comments_recent': article_comments_recent})
答案 0 :(得分:1)
所以我想出来了!我不得不混合几个不同的答案,但看起来解决方案如下:
我已经完成了很多.filter()。order_by()链,就像你在那里一样,并没有任何东西跳到我身边。我从来没有尝试过对模板进行排序而不进一步处理对象(通常迭代它们),所以我想知道order_by()是否会丢失作为django懒惰评估的一部分?也许尝试在list()中包装filter()。order_by()行来强制进行评估,而不是将其推迟到以后的某个时间?
via StackOverflow Question: "order_by() doesn't work with filter() in Django view"
article_comments_recent = ArticleComment.objects.filter(article=article).order_by('-created')
应该是:
article_comments_recent = list(ArticleComment.objects.filter(article=article).order_by('tree_id', 'level', '-created'))