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')
相关推荐
「QT(C++)开发工程师」4 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天4 小时前
0 初识C++
开发语言·c++
FfHUCisI5 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI5 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼5 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
卓怡学长6 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk6 小时前
ObjectProperty
java·开发语言·算法
大模型码小白6 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9506 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区