Using Django-MPTT in Django-Filters to get children on filtering parent node

1.2k Views Asked by At

I have an MPTT model class, and want to use it in Django-Filter.

My MPTT model is;

class ProdCategory(MPTTModel):
    name = models.CharField(max_length=200, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
    slug = AutoSlugField(populate_from='name',slugify=slugify)
    class MPTTMeta:
        order_insertion_by = ['name']
    def __str__(self):
        return self.name

The class is used as a foreign key in another "deal" model class as 'productCategory'

My filter class in filters.py is:

class DealFilter(django_filters.FilterSet):
    class Meta:
        model = deal
        fields = ['store', 'productCategory']

Finally, my view is:

def filterdeals(request):
    deals = deal.objects.all()
    myFilter = DealFilter(request.GET, queryset = deals)
    deals = myFilter.qs
    args = {
        "deals": deals, "myFilter":myFilter,}
    return render(request, 'deals/filter.html', args)
    

Now, since in MPTT, I want all the children selected on filtering the parent, I want to include this code for the same:

deal.objects.filter(productCategory__in=ProdCategory.objects.get(pk=2).get_descendants(include_self=True)) 

But I don't know where to include this code- so that when the parent category ID is passed, I get all the children under it.

TIA for your help

1

There are 1 best solutions below

0
On

Using filterset field with method will work in your case.

class DealFilter(django_filters.FilterSet):
    deep_search_field = django_filters.Charfield(method='search_children', Label='Category')
    class Meta:
        model = deal
        fields = ['store', 'productCategory', 'deep_search_field']
    def search_children(self, queryset, name, value):
        return queryset.filter(productCategory__in=ProdCategory.objects.get(pk=value).get_descendants(include_self=True))