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')
相关推荐
SimonKing3 小时前
Typora 收费,开源产品Textus或可替代,还支持AI
java·后端·程序员
泡海椒3 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
Rain的Java大神之路3 小时前
别再死背八股了:读完 Spring 7.0.8 源码,我学会了"改"框架
java·后端·面试
旖旎夜光3 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
codeejun4 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑5 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者13 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员13 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇14 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu15 小时前
python:DecisionTree
开发语言·后端·python·算法