Django Rest Framework之过滤器
一:原始过滤方法
默认情况下 DRF generic list view 会返回整个 queryset 查询结果,但通常业务只是需要其中一部分,这种情况下就需要使用 “过滤器” 来限制返回结果集。
最原始的方式是继承 GenericAPIView 类或使用继承了 GenericAPIView 的类,然后重写 .get_queryset() 方法 比如:
class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
# queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = Pagination
def get_queryset(self):
queryset = Goods.objects.all()
price_min = self.request.query_params.get('price_min', 0)
if price_min:
queryset = Goods.objects.filter(shop_price__gt = int(price_min))
return queryset
这里注意:由于在类中没有指定queryset,在访问接口时会报如下错误
assert queryset is not None, '`basename` argument not specified, and could ' \
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
解决方案是在路由中加basename参数:
from rest_framework.routers import DefaultRouter
from goods import views
router = DefaultRouter()
router