1.路由
from meiduo_admin.user.user_views import UsersView
urlpatterns = [
# 用户操作路由
path('users/', UsersView.as_view()),
]
2. 序列化器
from rest_framework import serializers
from meiduo_admin.models import User
class UsersSerialize(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'mobile', 'email', 'password']
# 1,给password增加额外的约束选项,不进行返回
extra_kwargs = {
"password": {
'write_only': True
}
}
# 1,重写create方法,密码加密
def create(self, validated_data):
return User.objects.create_user(**validated_data)
3. 视图
from rest_framework.generics import ListAPIView, CreateAPIView
from meiduo_admin import models
from meiduo_admin.user.user_serializers import UsersSerialize
from meiduo_admin.utils.myPagination import MyPageNumberPagination
class UsersView(ListAPIView, CreateAPIView):
pagination_class = MyPageNumberPagination
serializer_class = UsersSerialize
# queryset = models.User.objects.filter(is_staff=False).all().order_by('-date_joined')
# 1. 为了获取前端查询条件keyword重写get_queryset方法
def get_queryset(self):
# 2. 获取前端传入的参数keyword,名称由前端指定
keyword = self.request.query_params.get('keyword')
if keyword:
return models.User.objects.filter(is_staff=False, username__contains=keyword).all().order_by('-date_joined')
return models.User.objects.filter(is_staff=False).all().order_by('-date_joined')