设计RESTful风格的文档接口

1. 安装第三方库 djangorestframework

pip install djangorestframework

2. 注册rest_framework

# settings.py
INSTALLED_APPS = [
    'rest_framework'
]

3. 序列化模型

# serializers.py
from rest_framework import serializers
from car.models import Record

class RecordSerializer(serializers.ModelSerializer):

    class Meta:
        model = Record
        fields = '__all__'

4. 视图集

# views.py
from car.serializers import RecordSerializer

class SearchViewSet(ModelViewSet):
    queryset = Record.objects.all().order_by('-makedate')
    serialize_class = RecordSerializer
    
# urls.py
router = DefaultRouter()
router.register('records', SearchViewsSet)
urlpatterns += router.urls

5. CBV (Class-Based View) 代码量少,简单方便

# views.py
class SearchView(ListCreateAPIView, DestoryAPIView):
    queryset = Record.objects.all().order_by('-makedate')
    serialize_class = RecordSerializer
# urls.py
urlpatterns = [
  path('records', SearchView.as_view())
]

6. FBV (Function-Based View) 灵活,完全自己定制,但代码较多

# views.py
@api_view(['GET', 'POST'])
def search(request):
    if request.method == 'POST':
        record = Record()
        record.save()
        serializer = RecordSerializer(record)
    else:
        queryset = Record.objects.all()
        serializer = RecordSerializer(queryset, many=True)
    return Response(serializer.data)

7. 实现分页功能

# 设置默认分页
# settings.py

REST_FRAMEWORK = {
    # 每页显示5个结果 
    'PAGE_SIZE':5,
    'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination'
}
# 自定义分页
# views.py
class CustomPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    max_page_size = 50

class SearchViewSet(ModelViewSet):
    queryset = Record.objects.all().order_by('-makedate')
    serializer_class = RecordSerializer
    pagination_class = CustomPagination
    

8. 数据过滤

8.1 自定义过滤器

class RecordFilter(FilterSet):
    carno_or_owner = django_filters.CharFilter(method='search', label='输入车牌号或车主姓名')
    @staticmethod
    def search(queryset, name, value):
        return queryset.filter(Q(carno=normalize_carno(value)) |
                               Q(owner__icontains=value))

8.2 在视图集中加上过滤器

class SearchViewSet(ModelViewSet):
    # 获取所有对象
    # 数据序列化
    # 添加分页规则
    # 添加过滤器
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = RecordFilter
    # 可选过滤选择
    # filterset_fields = ('carno', 'owner', )
    # 默认排序方式
    ordering = ('-makedate', )
    # 可选排序方式
    ordering_fields = ('carno', 'makedate', )

你可能感兴趣的:(设计RESTful风格的文档接口)