嵌套对象的查询集排序

费多·伊万诺夫(Fedor Ivanov)

我需要使用REST API在我的项目中构建一个简单的嵌套注释系统。

有一些要求:

该页面应包含所有注释的分页,而不仅仅是父注释。因此,如果有1条评论和20条来自其他用户的嵌套评论,则应在首页上显示,如下所示:

-评论1

-子评论1

-...

-子评论9

在第二页上:

-子评论10

-...

-子评论19

在第三页上:

-子评论20

就最少的数据库访问而言,它应该是一个最佳的解决方案。

我想知道自定义Queryset的顺序,当每个注释之后跟随嵌套注释时,如下所示:

// Note, that ids follow in chaotic order
{
    id: 1,
    text: "Comment 1",
    parent: null
}, 
{
    id: 5,
    text: "Sub comment 1 for Comment 1",
    parent: 1
}, 
{
    id: 6,
    text: "Sub comment 2 for Comment 1",
    parent: 1
}, 
{
    id: 2,
    text: "Comment 2",
    parent: null
}, 
{
    id: 3,
    text: "Sub comment 1 for Comment 2",
    parent: 2
}, 
{
    id: 4,
    text: "Sub comment 2 for Comment 2",
    parent: 2
}, 

我也曾想过和google有关Django-mptt,但不知道如何实现它。您可以向我建议如何解决此问题并像我的示例中那样获取JSON吗?

您可能可以使用复合排序键<parent>_<id>为子级<id>注释注释集,仅对根注释进行注释,并以此排序。在示例中,注释将具有sort keys 1, 1_5, 1_6, 2, 2_3, 2_4

from django.db.models import CharField, Value as V
from django.db.models.functions import Concat

Comment.objects
    .annotate(sort_key=Case(
        When(parent__isnull=True, then=Concat('id', V('_0'), output_field=CharField())),
        When(parent__isnull=False, then=Concat('parent', V('_'), 'id', output_field=CharField())),
        output_field=CharField())
    .order_by('sort_key')

如果孩子可以id按日期排序,而不必按日期或类似日期排序,那么这当然是一个有效的解决方案如果您需要子级的另一个排序顺序,则可能需要在聚合中对其子级排序后,用索引显式注释它们。

看到:

编辑:将父母的排序键更改为1_0。通过int vs char比较解决了该问题。当然,演员阵容也可以。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章