python - django-mptt order_by() 在递归树期间不工作

标签 python html django

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

View .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>

最佳答案

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

I've done lots of .filter().order_by() chains just as you have them there, and nothing jumps out to me as out of place. I've never tried to carry that ordering over to the template without further processing the objects though (usually iterate over them), so I wonder if the order_by() is lost as part of django's lazy evaluation? Maybe try wrapping the filter().order_by() line in a list() to force evaluation there instead of it being put off till some later time?

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

关于python - django-mptt order_by() 在递归树期间不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901779/

相关文章:

python - 确定天空中的 eclipse

html - IE6/7右浮动bug

django - 如何检测 PyCharm 中未处理的异常?

python - 如何将数据发送到 Django 中的基本模板?

Python,如何扩展 Decimal 类以添加有用的方法

python - Windows 中 Python 长路径名出现 FileNotFoundError

html - 如何在 Firefox 中使用 CSS 为用户选择的选项着色

html - css: display:inline-block and span with position:relative 构建多列下拉列表

python - 在 Django 模板中将数字向下舍入到最接近的 1000

ajax - 在没有表单元素的 Django 中使用 ajax 请求