AutocompleteFilter self-recursive foreign key filter query for all parent show child names

6 views
Skip to first unread message

Mohammed Ezzi

unread,
Apr 1, 2022, 6:21:33 PMApr 1
to yourlabs
I wan't to make a filter on admin site where I filter categories by giving parent category name , the Category model has a self-recursive foreign key for parent category.
the model:
class Category(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey(
"self", on_delete=models.CASCADE, null=True, blank=True, related_name="childs"
)
description = models.TextField(null=True, blank=True)
is_adult = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
```
in **admin.py** :
``
class ParentCategoryFilter(AutocompleteFilter):
title = "By parent category"
field_name = "parent"
autocomplete_url = "parent-category-autocomplete"
is_placeholder_title = True


class CategoryAdmin(admin.ModelAdmin):
search_fields = ["name"]
autocomplete_fields = ["parent"]
fieldsets = (
(
_("Details"),
{
"fields": (
"name",
"parent",
"description",
),
},
),
)
list_display = (
"name",
"parent",
)
list_filter = [ParentCategoryFilter]


admin.site.register(Category, CategoryAdmin)
```
and the views.py where `ParentCategoryFilter` is defined:
``
class ParentCategoryAutocompleteView(autocomplete.Select2QuerySetView):
permissions = [
"CategoryView",
]

def get_queryset(self):
qs = Category.objects.filter(parent__isnull=True)
if self.q:
qs = qs.filter(Q(name__istartswith=self.q))
return qs

the problem I get is that in the filter I get the child's categories name. I don't know what the problem with it.
Screenshot from 2022-04-01 22-20-33.png
Reply all
Reply to author
Forward
0 new messages