Reputation: 41
can anyone help with filtering in DRF.
I have some products models, say Product
and manager ProductManager
:
class ProductItem(Model):
price = DecimalField()
class Product(Model):
items = ManyToManyField(ProductItem)
priceman = ProductManager()
class ProductManager(Manager):
def get_queryset(self):
qs = super().get_queryset().annotate(total_price=Sum('items__price'))
return qs
Here if filter class:
class ProductFilter(django_filters.rest_framework.FilterSet):
class Meta:
model = Product
fields = {
'total_price': ['lt', 'gt'],
}
Here is view:
class ProductViewSet(ModelViewSet):
queryset = Product.priceman.all()
filterset_class = ProductFilter
and I get the error:
TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: total_price
How should I configure the filter class to make this work?
Upvotes: 2
Views: 1678
Reputation: 41
I found answer, this can be done by changing filter class like this:
class ProductFilter(django_filters.rest_framework.FilterSet):
min_price = NumberFilter(field_name="total_price", lookup_expr='gt')
max_price = NumberFilter(field_name="total_price", lookup_expr='lt')
class Meta:
model = Product
fields = ['min_price', 'max_price']
Upvotes: 2