使用django-filter的DRF注释查询集过滤

时间:2018-10-30 11:29:58

标签: django django-rest-framework django-filter django-annotate

任何人都可以帮助DRF进行过滤。 我有一些产品模型,例如Product和经理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

如果是过滤器类:

class ProductFilter(django_filters.rest_framework.FilterSet):
    class Meta:
        model = Product
        fields = {
            'total_price': ['lt', 'gt'],
        }

这是视图:

class ProductViewSet(ModelViewSet):
    queryset = Product.priceman.all()
    filterset_class = ProductFilter

我得到了错误:

TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: total_price

我应该如何配置过滤器类以使其起作用?

1 个答案:

答案 0 :(得分:1)

我找到了答案,这可以通过更改过滤器类来完成:

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']