rest_framework--过滤器get_queryset

drf过滤–get_queryset

  • 过滤queryset

    from rest_framework.pagination import PageNumberPagination
    from rest_framework import mixins
    from rest_framework import viewsets
    
    from .models import Goods
    from .serializers import GoodsSerializer
    
    
    class GoodsPagination(PageNumberPagination):
        page_size = 10
        page_size_query_param = "page_size"
        page_query_param = "p"
        max_page_size = 100
    
    
    class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
        # 指定queryset
        # queryset = Goods.objects.all()
    
        # 指定序列化类
        serializer_class = GoodsSerializer
    
        # 指定分页类
        pagination_class = GoodsPagination
    		
        # 这里用了get_queryset来指定queryset 那么我们上面的query_set可以省略不写, 但是前提是在注册路由是需要加个base_name
        def get_queryset(self):
            return Goods.objects.filter(shop_price__gt=100)
    
  • url

    from django.conf.urls import url, include
    
    from rest_framework.routers import DefaultRouter
    
    from goods.views import GoodsListViewSet
    # 生成一个注册器实例对象
    router = DefaultRouter()
    # 将需要自动生成url的接口注册, 指定base_name
    # 配置goods的url
    router.register(r'goods', GoodsListViewSet, base_name="goods-list")
    
    urlpatterns = [
        # 自动生成url
        url(r"^", include(router.urls)),
    ]
    
  • settings

    INSTALLED_APPS = [
        'rest_framework',
    ]
    

你可能感兴趣的:(#,rest_framework)