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')
相关推荐
2501_944521592 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理2 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
wangchunyu1143 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
paopaokaka_luck4 小时前
流浪动物救助与收养系统(DeepSeek AI对话、 ECharts多维分析、救助流程衔接、领养与回访衔接、 捐赠确认与公示、志愿者协作)
java·前端·javascript·人工智能·mysql·echarts·推荐算法
Thomas.Sir4 小时前
第9课:SpringBoot4.x Web开发基础:WebMvc自动配置、静态资源、请求参数接收
java·spring boot
程序 代码狂人4 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
2501_944521595 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
meiying88386 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
@大迁世界6 小时前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper6 小时前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash