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')
相关推荐
必须会一定会1 小时前
Agent Plugins 1.0实战:plugin.json、skills、mcp.json目录结构与迁移
开发语言·人工智能·ai编程
St_rive1 小时前
Page Object设计模式
java·开发语言·设计模式
wp123_12 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记
wuyk5552 小时前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
风流 少年2 小时前
Spring AI 2.0:SSE
java·人工智能·spring
凤山老林2 小时前
精细化流量治理:Spring Boot 动态特性开关与灰度发布体系
java·spring boot·后端
luj_17683 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
caimouse4 小时前
ReactOS 图形系统分析(16):字符串对象 — STROBJ(string.c)
c语言·开发语言
Aphelios3804 小时前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽