开发者

django-threadedcomments to order comments differently

I'm using

{% g开发者_如何转开发et_threaded_comment_tree for OBJECT [TREE_ROOT] as CONTEXT_VAR %}:

to get a list of all my comments for a specific object. This works great, but I want to get the most recent on the top of my list. By default this returns the oldest on the top of the list. Any ideas on how can I achieve this.


This is my version of CommentListNode in threadedcomments_tags.py that do the trick:

class CommentListNode(BaseThreadedCommentNode):
    """
    Insert a list of comments into the context.
    """

    def __init__(self, flat=False, root_only=False, newest = True, **kwargs):
        self.flat = flat
        self.newest = newest
        self.root_only = root_only
        super(CommentListNode, self).__init__(**kwargs)

    def handle_token(cls, parser, token):
        tokens = token.contents.split()

        extra_kw = {}
        if tokens[-1] in ('flat', 'root_only'):
            extra_kw[str(tokens.pop())] = True

        if len(tokens) == 5:
            comment_node_instance = cls(
                object_expr=parser.compile_filter(tokens[2]),
                as_varname=tokens[4],
                **extra_kw
            )
        elif len(tokens) == 6:
            comment_node_instance = cls(
                ctype=BaseThreadedCommentNode.lookup_content_type(tokens[2],
                    tokens[0]),
                object_pk_expr=parser.compile_filter(tokens[3]),
                as_varname=tokens[5],
                **extra_kw
            )
        else:
            raise template.TemplateSyntaxError(
                "%r tag takes either 5 or 6 arguments" % (tokens[0],))
        return comment_node_instance

    handle_token = classmethod(handle_token)

    def get_context_value_from_queryset(self, context, qs): 
        if self.newest:
            qs = qs.extra(select={ 'tree_path_root': 'SUBSTRING(tree_path, 1, %d)' % PATH_DIGITS }).order_by('%stree_path_root' % ('-'), 'tree_path')  
        elif self.flat:
            qs = qs.order_by('-submit_date')
        elif self.root_only:
            qs = qs.exclude(parent__isnull=False).order_by('-submit_date')
        return qs


The following snippet works for me, it will sort the a comment queryset (qs) according to newest first, keeping the nested comments (replies) in their proper hierarchical order.

You will need to encapsulate this in a template tag to make this usable from inside a template...

from django.contrib import comments
from threadedcomments.models import PATH_DIGITS

comment_model = comments.get_model()
newest = True
qs = comment_model.objects.filter(content_type=ctype,
                                  object_pk=discussion.pk).select_related()
qs = qs.extra(select={ 'tree_path_root': 'SUBSTRING(tree_path, 1, %d)' % PATH_DIGITS }) \
    .order_by('%stree_path_root' % ('-' if newest else ''), 'tree_path')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜