我正在为我的评论应用程序使用django-mptt包,我有以下模型:
class Comment(MPTTModel):
content = models.TextField(verbose_name='Treść')
author = models.ForeignKey(AUTH_USER_MODEL, verbose_name='Autor', blank=False, null=True)
is_deleted = models.BooleanField(verbose_name='Komentarz usunięty', default=False,
help_text='Zaznacz, aby usunąć komentarz')
ip = models.GenericIPAddressField(default=0, verbose_name='Adres IP')
content_type = models.ForeignKey(ContentType, verbose_name='Typ obiektu')
object_id = models.PositiveIntegerField(verbose_name='ID obiektu')
content_object = GenericForeignKey('content_type', 'object_id')
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
hotness = models.FloatField(default=0)
created_at = models.DateTimeField(auto_now_add=False, verbose_name='Data dodania')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Aktualizacja')
class MPTTMeta:
order_insertion_by = ('-hotness', '-created_at')
class Meta:
verbose_name = 'Komentarz'
verbose_name_plural = 'Komentarze'
def __unicode__(self):
if len(self.content) > 50:
return self.content[:50] + '...'
else:
return self.content
我想让用户可以通过热度或创建日期对评论树进行排序。是否可以从视图中编辑order_insertion_by
字段以生成2种类型的排序(按日期,按热度)?谢谢你的帮助。
答案 0 :(得分:3)
Modified Preorder Tree Traversal
(MPTT)是一种检索树结构的方法,其中一个查询使用左(lft
in mptt)和右(rgt
)编号,如下所示{{3 }}
定义多个order_insertion_by将执行以下操作(根据mptts评论):
"""
Creates a filter which matches suitable right siblings for ``node``,
where insertion should maintain ordering according to the list of
fields in ``order_insertion_by``.
For example, given an ``order_insertion_by`` of
``['field1', 'field2', 'field3']``, the resulting filter should
correspond to the following SQL::
field1 > %s
OR (field1 = %s AND field2 > %s)
OR (field1 = %s AND field2 = %s AND field3 > %s)
"""
如果我理解正确,order_insertion_by
指定兄弟姐妹的顺序,它代表父元素的子元素(而不是后代)。如果您需要两个不同的订单,lft
和rgt
也必须更改,因此它是第二个树。这不包括在mptt。
你仍然可以
Comment.objects.all().order_by('-hotness')
但你会丢失树形结构。通常不可能通过其他方式维护树结构并对整个树进行排序,例如,辣味。想象一下,你有以下几点:
Comment1 (hotness 0)
Comment2 (hotness 2, child of Comment1)
Comment3 (hotness 1)
会导致
Comment2
Comment3
Comment1
已订购,但Comment2
未附加Comment1
。
如果要在兄弟级别的基础上使用order_insertion_by
定义的其他内容进行排序,请获取以下内容:
Comment3
Comment1
Comment2
可能会编写一个新的模板标记,如{% recursetree objects -hotness %}
,它会迭代并重新排序children
元素并返回新树。它仍然是一个数据库查询 - 但我无法估计性能损失。
您必须按照以下方式分叉并编辑mptt_tags.py
:
class RecurseTreeNode(template.Node):
def __init__(self, template_nodes, queryset_var, order_var=None):
self.template_nodes = template_nodes
self.queryset_var = queryset_var
self.order_var = order_var
def _render_node(self, context, node):
bits = []
context.push()
children = node.get_children()
if children and self.order_var is not None:
children = children.order_by(self.order_var)
for child in children:
bits.append(self._render_node(context, child))
context['node'] = node
context['children'] = mark_safe(''.join(bits))
rendered = self.template_nodes.render(context)
context.pop()
return rendered
def render(self, context):
queryset = self.queryset_var.resolve(context)
roots = cache_tree_children(queryset)
bits = [self._render_node(context, node) for node in roots]
return ''.join(bits)
@register.tag
def recursetree(parser, token):
bits = token.contents.split()
if len(bits) < 2:
raise template.TemplateSyntaxError(_('%s tag requires a queryset') % bits[0])
queryset_var = template.Variable(bits[1])
if len(bits) == 3:
order_var = bits[2]
else:
order_var = None
template_nodes = parser.parse(('endrecursetree',))
parser.delete_first_token()
return RecurseTreeNode(template_nodes, queryset_var, order_var)