【问题标题】:django-mptt order_by() Not Working During recursetreedjango-mptt order_by() 在递归树期间不工作
【发布时间】:2015-11-24 19:04:23
【问题描述】:

我目前正在使用django-mptt Django 包,我正在尝试针对过滤器运行.order_by(),但它不起作用 - 更具体地说,无论我使用什么order_by(),顺序都保持不变。这是我当前的代码:

views.py

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

_article-modal.html

<ul class="root">
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

【问题讨论】:

    标签: python html django


    【解决方案1】:

    所以我想通了!我不得不混合几个不同的答案,但看起来解决方案如下:

    我已经完成了很多 .filter().order_by() 链,就像你有它们一样,没有什么东西让我觉得不合适。我从来没有尝试过在不进一步处理对象的情况下将这种排序转移到模板中(通常迭代它们),所以我想知道 order_by() 是否作为 django 惰性评估的一部分丢失了?也许尝试将 filter().order_by() 行包装在 list() 中以强制评估而不是将其推迟到稍后的时间?

    via * 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'))
    

    【讨论】:

      最近更新 更多