2010-10-04 93 views
1

我使用Django的threadedcomments訂購不同

{% get_threaded_comment_tree for OBJECT [TREE_ROOT] as CONTEXT_VAR %}: 

讓我爲特定對象的所有意見的列表意見。這很好用,但我想在列表頂部找到最新的內容。默認情況下,這將返回列表頂部的最早的。關於如何實現這一點的任何想法。

回答

0

下面的代碼片段適用於我,它會根據最新的第一個對評論查詢集(qs)進行排序,並將嵌套的評論(回覆)保留爲正確的層次結構。

您將需要封裝這個模板中的標籤,使從模板中使用這個...

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

這是我的版本CommentListNode的threadedcomments_tags.py該做的伎倆:

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