AutocompleteFilter self-recursive foreignkey filter query for all parent

431 views Asked by At

I wan't to make a filter on categories by parent category, I use a model and for parent category I linked it to itself.
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 url to the views is:

urlpatterns = [
    url(
        "^/autocomplete",
        
staff_permission_required(ParentCategoryAutocompleteView.permissions)(
            ParentCategoryAutocompleteView.as_view()
        ),
        name="parent-category-autocomplete",
    ),

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. enter image description here

1

There are 1 answers

1
noes1s On

If your not using, calling on , or representing the category model object default name anywhere else. One simple modification would be to add a default string name to 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)

    def __str__(self):
        if self.parent != None:
            return self.parent.name
        else:
            return self.name

This is a quick and dirty solution. If you are not able to use this solution I will look into this further.