django drf SearchFilter与OrderingFilter

Posted chenyishi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django drf SearchFilter与OrderingFilter相关的知识,希望对你有一定的参考价值。

View Demo

from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework import mixins, generics
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from goods.models import Goods, GoodsCategory
from goods.serializer import GoodsSerializer, CategorySerializer
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend

import django_filters
from rest_framework import filters

class GoodsList(mixins.ListModelMixin, viewsets.GenericViewSet):
    class GoodsPagination(PageNumberPagination):
        page_size = 2
        page_size_query_param = pageSize
        page_query_param = p
        max_page_size = 100

    queryset = Goods.objects.all()  # 不能切片后再过滤,例如:Goods.objects.all()[:10]
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    search_fields = (=name,) # 文档:https://www.django-rest-framework.org/api-guide/filtering/#searchfilter
    ordering_fields=(name,)
    # filter_fields = (‘name‘,) #逗号必加,缺点无法模糊查询
    # filterset_class = GoodsFilter

test

技术图片

 

以上是关于django drf SearchFilter与OrderingFilter的主要内容,如果未能解决你的问题,请参考以下文章

在 django rest 框架中定义 searchFilter URL

drf-过滤组件

是否可以将 FastAPI 与 Django 一起使用?

django drf GenericAPIView和ListAPIView

django drf 基础学习4

drf 使用filter_backends 搜索过滤