Hybrid
Hybrid

Reputation: 7049

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. Here is my current code:

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>

Upvotes: 1

Views: 245

Answers (1)

Hybrid
Hybrid

Reputation: 7049

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

Should be:

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

Upvotes: 1

Related Questions