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
Using filterset field with method will work in your case.