我在我的 Django 应用程序中使用 django-mptt 作为文章模型。如果我想获取所有设置为例如隐藏的文章,我可以这样做
Article.objects.filter(hidden=False)
但这会破坏 mptt 树。如何以这样的方式过滤我的查询集,不仅排除所有隐藏的文章,而且排除这些节点的子节点,并以这种方式保持树的完整性,以便我仍然可以使用 tree_info 模板标签?
最佳答案
我有一个类似的问题。我想删除一个节点及其所有子节点。
这是我如何设法做到这一点:
class FolderForm(forms.ModelForm):
class Meta:
model = Folder
fields = ('name', 'parent')
def __init__(self, *args, **kwargs)
super(FolderForm, self).__init__(*args, **kwargs)
if self.instance is not None:
exclude_ids = [f.id for f in self.instance.get_descendants(
include_self=True)]
self.fields['parent'].queryset = self.fields['parent'].queryset \
.exclude(pk__in=exclude_ids)
关于django-mptt 过滤器而不破坏树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12370695/