使用TreeManager遇到一个奇怪的问题
这是我的代码:
# other imports
from mptt.models import MPTTModel, TreeForeignKey
from mptt.managers import TreeManager
class SectionManager(TreeManager):
def get_queryset(self):
return super().get_queryset().filter(published=True)
class Section(MPTTModel):
published = models.BooleanField(
default=True,
help_text="If unpublished, this section will show only"
" to editors. Else, it will show for all."
)
objects = TreeManager()
published_objects = SectionManager()
当我测试它时。我得到以下正确结果:
# show all objects
Section.objects.count() # result is correct - 65
Section.objects.root_nodes().count() # result is correct - 12
# show published objects, just one is not published.
Section.published_objects.count() # result is correct - 64
Section.published_objects.root_nodes().count() # result is corrct - 12
但其中一个根的子代尚未发布,并且未在结果中显示。这是测试:
for root in Section.objects.root_nodes():
print(f"root_section_{root.id} has {root.get_children().count()} children")
# results ...
root_section_57 has 13 children # correct - 13 items
# ... more results
for root in Section.published_objects.root_nodes():
print(f"root_section_{root.id} has {root.get_children().count()} children")
# results ...
root_section_57 has 13 children # WRONG - should be only 12 children
# ... more results
我可能不了解某些内容,或者我遇到了错误? 有什么想法吗?
注意::此问题已发布在django-mptt github问题页面上,网址为https://github.com/django-mptt/django-mptt/issues/689
答案 0 :(得分:0)
https://github.com/django-mptt/django-mptt/blob/master/mptt/managers.py
您将覆盖错误的函数调用。 root_nodes()
致电._mptt_filter()
@delegate_manager
def root_nodes(self):
"""
Creates a ``QuerySet`` containing root nodes.
"""
return self._mptt_filter(parent=None)
您的_mptt_filter
没有给定的qs
。
@delegate_manager
def _mptt_filter(self, qs=None, **filters):
"""
Like ``self.filter()``, but translates name-agnostic filters for MPTT
fields.
"""
if qs is None:
qs = self
return qs.filter(**self._translate_lookups(**filters))
现在,您需要根据用例进行自定义。
希望可以有所帮助