如果某个API需要传递一些条件进行搜索,其实就在是URL后面通过GET传参即可,例如:

    1. /api/users?age=19&category=12

    image-20210825200814769.png

    在drf中也有相应组件可以支持条件搜索。

    1. # urls.py
    2. from django.urls import path
    3. from app01 import views
    4. urlpatterns = [
    5. path('api/users/', views.UserView.as_view(
    6. {"get": "list", "post": "create"}
    7. )),
    8. path('api/users/<int:pk>/', views.UserView.as_view(
    9. {"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"}
    10. )),
    11. ]
    1. # views.py
    2. from rest_framework import serializers
    3. from rest_framework.viewsets import ModelViewSet
    4. from rest_framework.filters import BaseFilterBackend
    5. from app01 import models
    6. class UserModelSerializer(serializers.ModelSerializer):
    7. level_text = serializers.CharField(
    8. source="get_level_display",
    9. read_only=True
    10. )
    11. extra = serializers.SerializerMethodField(read_only=True)
    12. class Meta:
    13. model = models.UserInfo
    14. fields = ["username", "age", "email", "level_text", "extra"]
    15. def get_extra(self, obj):
    16. return 666
    17. class Filter1(BaseFilterBackend):
    18. def filter_queryset(self, request, queryset, view):
    19. age = request.query_params.get('age')
    20. if not age:
    21. return queryset
    22. return queryset.filter(age=age)
    23. class Filter2(BaseFilterBackend):
    24. def filter_queryset(self, request, queryset, view):
    25. user_id = request.query_params.get('id')
    26. if not user_id:
    27. return queryset
    28. return queryset.filter(id__gt=user_id)
    29. class UserView(ModelViewSet):
    30. filter_backends = [Filter1, Filter2]
    31. queryset = models.UserInfo.objects.all()
    32. serializer_class = UserModelSerializer
    33. def perform_create(self, serializer):
    34. """ 序列化:对请求的数据校验成功后,执行保存。"""
    35. serializer.save(depart_id=1, password="123")