2

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?

1 Answer 1

2

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.