任何人都可以帮助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
我应该如何配置过滤器类以使其起作用?
答案 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']