如何使用Django的mptt查询节点所有子节点的对象?

2024-04-28 21:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Django mppt获取Django上给定节点的所有子节点的对象

我有一个如下所示设计的模型,具有相同缩进级别的类/类别(节点)定义同级,内部缩进是子级。用类别标记的对象显示在类别(节点)的正下方。对象以-符号开头。类/类别(节点)旁边的数字是id。

所有节点都是给定idCategory类的实例。

high school (1)
    class 8 (2)
        division a (3)
            -Billie
            -Tre
            -Mike

        division b (4)
            -Patrik
            -Pete
            -Andy
    class 9 (3)
        division a (8)
            -Mark
            -Tom
            -Travis

        division b (5)
            -Gerard
            -Frank
            -Mikey

    class 10  (4)
        division a (6)
            -Hayley
            -Jeremy
            -Taylor

        division b (7)
            -Steven
            -Slash
            -Izzy

我可以用这种方法得到特定节点的查询集

>>> Category.objects.get(pk=7).product_set.all()
[Steven, Slash, Izzy]


>>> Category.objects.get(pk=4).product_set.all()
[Mark, Tom, Travis]

如何使用pk=1pk=2pk=3pk=4查询以获取所有子对象?

例如

查询pk=2必须返回

[Billie, Tre, Mike, Patrik, Pete, Andy]

Tags: 对象djangoid节点类别classdivisiontre
3条回答

Category.objects.get(pk=1).get_leafnodes()是你要找的。

django-mptt docs

Django mptt提供了两种检索子级的方法。

docs

MPTTModel.get_children(*args, **kwargs)

Returns a QuerySet containing the immediate children of this model >instance, in tree order.

The benefit of using this method over the reverse relation provided by the ORM to the instance’s children is that a database query can be avoided in the case where the instance is a leaf node (it has no children).

If called from a template where the tree has been walked by the cache_tree_children filter, no database query is required.

以及

MPTTModel.get_leafnodes(*args, **kwargs)

Creates a QuerySet containing leafnodes of this model instance, in tree order.

If include_self is True, the QuerySet will also include this model instance (if it is a leaf node)

我不知道你的模型是如何建立的,但我不知道你为什么在这里使用mptt。您使用的是类别/产品,但似乎是学生或人员和工作组。

也许您可以定义EstablishmentLevelLevel|StudentGroupStudent模型,而不是使用mptt函数查询,例如:

Student.objects.filter(studentgroup__level__pk=1)

Django doc

希望有帮助

Category.objects.get(pk=2).get_descendants(include_self=True)

这将得到所有类别的后代,包括self。

假设您的产品模型具有外键类别,则可以使用:

Product.objects.filter(category__in=Category.objects.get(pk=2)\
    .get_descendants(include_self=True))

相关问题 更多 >