4

I'm using django-mptt for a Article model in my Django application. If I want to get all Articles which are set to for example hidden, I could do

Article.objects.filter(hidden=False)

but that would break the mptt-tree. How can I filter on my queryset in such a way that not only does it exclude all hidden articles, but also the childs of those nodes and that way maintain the integrity of the tree so that I still can use the tree_info template tag?

2 Answers2

1

I am having a similar issue. I would like to remove a node and all of its children.

Here is how I manage to do that:

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)
Natim
  • 17,274
  • 23
  • 92
  • 150
0

There is a simpler solution: just set all the children to hidden as well.

quantum
  • 3,672
  • 29
  • 51