python – Filtering filter list in django-filter

Question:

Hello I have a filterable model

class Sku(object):
    manufacturer = ForeignKey(SomeModel)

I want to filter by the manufacturer field, but taking into account only those manufacturers that the displayed Sku have, can you tell me where to look? A bit of code about which we are talking:

class SkuFilter(django_filters.FilterSet):
    # manufacturer__title = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Sku
        fields = ['manufacturer', ]


# кусок из views 
# ...
     c['skus'] = self.object.skus.filter(hide=False, prices__price_type=PRICE_ROZN).prefetch_related('prices',
                                                                                                        'stock').all().order_by(
            'prices__value')
        sku_filter = SkuFilter(self.request.GET, c['skus'])
# ...

That is, as a result, there may be 4 products in c ['skus'], and all manufacturers are displayed in the filter, and only those that these four products have are needed.

Answer:

I did it this way: I created the field I needed without a filter, the magic of the metaclasses did its job and created a base_filter, changed the selection.

class SkuFilter(django_filters.FilterSet):
    def __init__(self, data=None, queryset=None, prefix=None, strict=None):
        self.base_filters['manufacturer'] = django_filters.filters.ModelMultipleChoiceFilter(
            name='manufacturer',
            to_field_name='title',
            queryset=Manufacturer.objects.filter(
                pk__in=queryset.values_list('manufacturer').distinct()),
        )
        super().__init__(data, queryset, prefix, strict)

    manufacturer = django_filters.filters.ModelMultipleChoiceFilter(
        name='manufacturer',
        to_field_name='title',
        queryset=Manufacturer.objects.all()
    )

    class Meta:
        model = Sku
        fields = ['manufacturer', ]
Scroll to Top
AllEscort