Django的查询所有,根据用户名查询,增加用户操作

1.路由

python 复制代码
from meiduo_admin.user.user_views import UsersView

urlpatterns = [

    # 用户操作路由
    path('users/', UsersView.as_view()),
]
  1. 序列化器
python 复制代码
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)
  1. 视图
python 复制代码
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')
相关推荐
踩着两条虫6 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB6 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
budingxiaomoli6 小时前
Spring IoC &DI
java·spring·ioc·di
Spider Cat 蜘蛛猫6 小时前
Springboot SSO系统设计文档
java·spring boot·后端
未若君雅裁6 小时前
MySQL高可用与扩展-主从复制读写分离分库分表
java·数据库·mysql
即使再小的船也能远航6 小时前
【Python】安装
开发语言·python
学习中.........6 小时前
从扰动函数的变化,感受红黑树带来的性能提升
java
Irissgwe6 小时前
类与对象(三)
开发语言·c++·类和对象·友元
计算机安禾7 小时前
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
java·c++·算法
雪度娃娃7 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++