from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
# 定义模型查询集
queryset = YourModel.objects.all()
# 序列化器
class YourSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = '__all__' # 或者列出所有你想要暴露的字段
# 分页配置
class StandardResultsSetPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 1000
# 视图
class YourListView(generics.ListAPIView):
queryset = YourModel.objects.all()
serializer_class = YourSerializer
pagination_class = StandardResultsSetPagination
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_fields = ['field1', 'field2']
search_fields = ['field1', 'field2']
ordering_fields = ['field1', 'field2']
这个代码实例展示了如何在Django REST framework中配置分页、过滤和搜索功能。首先定义了一个自定义的分页类StandardResultsSetPagination
,设置了每页的大小和查询参数。在视图YourListView
中,我们使用了分页类,并添加了过滤、搜索和排序功能的后端配置。这些配置可以根据实际模型和需求进行调整。