[Django]-How to override (filter based on particular condition) Django admin filter choices?

4👍

Sub-classing “admin.RelatedOnlyFieldListFilter” and overriding emthod “field_choices” worked!

class CustomRelatedOnlyFieldListFilter(admin.RelatedOnlyFieldListFilter):

    def field_choices(self, field, request, model_admin):
        custom_qs = model_admin.get_queryset(request).exclude(
            vendorproduct=None
        )
        pk_qs = custom_qs.distinct().values_list(
            'brand__pk', flat=True
        )
        return field.get_choices(include_blank=False, limit_choices_to={'pk__in': pk_qs})

And the admin will be:

class StandardProductModelAdmin(admin.ModelAdmin):

    list_filter [
        ('brand', CustomRelatedOnlyFieldListFilter),
    ]
👤Javed

0👍

You can achieve that by writing a custom list filter (let’s say CustomStanardProductFilter) and then using it in your list_filter:

from django.contrib.admin import SimpleListFilter

class CustomStanardProductFilter(SimpleListFilter):
    def lookups(self, request, model_admin):
        ...

    def queryset(self, request, queryset):
        ...

class StandardProductModelAdmin(admin.ModelAdmin):
    list_filter [
        'CustomStanardProductFilter'
    ]

For full example, see this.

Hope it helps.

Leave a comment