简体   繁体   English

django-mptt order_by()在递归树期间不起作用

[英]django-mptt order_by() Not Working During recursetree

I am currently using the django-mptt Django package, and I am trying to run .order_by() against a filter but it is not working - more specifically, the order stays the same no matter what order_by() I use. 我当前正在使用django-mptt Django程序包,并且我正在尝试对过滤器运行.order_by() ,但无法正常工作-更具体地说,无论我使用什么order_by() ,顺序都保持不变。 Here is my current code: 这是我当前的代码:

views.py 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 _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>

So I just figured it out! 所以我才想通! I had to mix a few different answers, but it looks like the solution is as follows: 我不得不混合几个不同的答案,但是看起来解决方案如下:

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. 我已经完成了许多.filter()。order_by()链,就像您在那儿一样,没有任何东西会跳到我那儿。 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? 我从来没有尝试过将顺序转移到模板上,而无需进一步处理对象(通常在对象上进行迭代),所以我想知道是否由于django的惰性评估而丢失了order_by()? 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? 也许尝试将filter()。order_by()行包装在list()中以强制进行评估,而不是推迟到以后再进行评估?

via StackOverflow Question: "order_by() doesn't work with filter() in Django view" 通过StackOverflow问题:“ order_by()在Django视图中无法与filter()一起使用”

article_comments_recent = ArticleComment.objects.filter(article=article).order_by('-created')

Should be: 应该:

article_comments_recent = list(ArticleComment.objects.filter(article=article).order_by('tree_id', 'level', '-created'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM