gpt4 book ai didi

python - django-mptt 多树和查询集

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:54 25 4
gpt4 key购买 nike

我的模型类可以包含多棵树。

class MyClass(MPTTModel, AbstractClass):
"""
"""
name = models.CharField(_('name'), max_length=255)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
***

我想我可以这样做:

nodes = MyClass.objects.filter(tree_id=1)

并使用:

nodes.get_root(), nodes.get_children(), etc,

但是我有

str: 'QuerySet' object has no attribute 'get_root'

阅读文档“MPTTModel 的子类具有以下实例方法:*

如何在一个模型类中使用具有多个树的方法?

谢谢!

最佳答案

您正在 queryset 上调用 get_root() 和其他方法。相反,您需要在模型实例上调用它们。要通过 id 获取实例,请使用 get() :

node = MyClass.objects.get(tree_id=1)
node.get_root()

或者,如果您是 filtering multiple objects ,循环生成的查询集:

nodes = MyClass.objects.filter(some_conditions)
for node in nodes:
node.get_root()

关于python - django-mptt 多树和查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24168025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com