我正在使用
{% get_threaded_comment_tree for OBJECT [TREE_ROOT] as CONTEXT_VAR %}:
获取特定对象的所有评论列表。这很好用,但我希望在列表的顶部获得最新版本。默认情况下,它返回列表顶部的最旧值。关于如何实现这一点的任何想法。
答案 0 :(得分:1)
这是我在threadedcomments_tags.py中的CommentListNode版本,可以解决这个问题:
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
答案 1 :(得分: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')