* 新建`ViewSet`
修改文件`/api/views.py`
```python
from rest_framework import viewsets, permissions
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from .serializers import *
from .models import *
class CustomPagination(PageNumberPagination):
page_size = 15
page_query_param = 'p'
page_size_query_param = 'page_size'
max_page_size = 19820
class PageRolesViewSet(viewsets.ModelViewSet):
queryset = PageRoles.objects.all()
serializer_class = PageRolesSerializer
pagination_class = CustomPagination
permission_classes = [permissions.IsAuthenticated]
filter_backends = [DjangoFilterBackend]
filter_fields = ['name', 'roles']
def get_queryset(self, *args, **kwargs):
search = self.request.query_params.get("search")
if search:
return PageRoles.objects.filter(Q(name__icontains=search) | Q(roles__icontains=search))
return PageRoles.objects.all()
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all().order_by('-date_joined')
serializer_class = UserProfileSerializer
pagination_class = CustomPagination
permission_classes = [permissions.IsAuthenticated]
filter_backends = [DjangoFilterBackend]
filter_fields = ['username', 'name']
def get_queryset(self, *args, **kwargs):
search = self.request.query_params.get("search")
if search:
return UserProfile.objects.filter(Q(name__icontains=search) | Q(username__icontains=search)).order_by(
'-date_joined')
return UserProfile.objects.all().order_by('-date_joined')
```