1👍
✅
In django-filter
you can specify keyword argument named as method
inside field which accepts either a callable or the name of a method so you camodify you ProductFilter
like this
class ProductFilter(django_filters.FilterSet):
CHOICE = {
('True', 'previously purchased'),
('False', 'all')
}
name = django_filters.CharFilter()
previously_purchased = django_filters.ChoiceFilter(
choices=CHOICE,
method='filter_previously_purchased',
)
def filter_previously_purchased(self, queryset, name, value):
if value == 'True':
transactions = Transaction.objects.filter(user_id=self.request.user).values_list('product_id')
queryset = queryset.filter(pk__in=[q[0] for q in transactions])
return queryset
class Meta:
model = Product
fields = ['name', 'previously_purchased',]
In above code I’ve added your show_products()
logic inside filter_previously_purchased
function with which takes these arguments
queryset
It is queryset of specifiedmodel
eg.Product.objects.all()
name
it’s a field name eg.previously_purchased
value
it’s value which comes from client.
Source:stackexchange.com