用户管理-分页

定义模型类

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone


# Create your models here.

# 用户
class User(AbstractUser):
    mobile = models.CharField('手机号', max_length=11)
    last_login = models.DateTimeField('上次登录时间', default=timezone.now)

    class Meta:
        db_table = 'user'


# 权限类
class PermissionType(models.Model):
    name = models.CharField('权限类型', max_length=30)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'permission_type'


# 权限
class Permission(models.Model):
    name = models.CharField('权限名称', max_length=30)
    code_name = models.CharField('权限', max_length=100)
    type_name = models.ForeignKey(PermissionType, on_delete=models.CASCADE, verbose_name='权限类行')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'permission'


# 用户组
class UserGroup(models.Model):
    name = models.CharField('组名', max_length=30)
    user = models.ManyToManyField(User)
    # 多对多
    permission = models.ManyToManyField(Permission)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'usergroup'

配置项目

AUTH_USER_MODEL = 'users.user'

写入一个序列化器

import re

from rest_framework import serializers
from users.models import User
from rest_framework.exceptions import ValidationError


# 用户信息
class UserSer(serializers.ModelSerializer):
	# 只写不读
    password = serializers.CharField(max_length=64, write_only=True, trim_whitespace=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'email', 'date_joined', 'last_login']
        # 只读不写
        read_orly_fields = ['id']

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        mobile = attrs.get('mobile')
        email = attrs.get('email')

        if not all(['username', 'password', 'mobile', 'email']):
            raise ValidationError('数据不能为空')

        if not re.findall(r'^\w{5,20}$', username):
            raise ValidationError('用户名不符合')

        if not re.findall(r'^[\w!@#$%^&*]{8,20}$', password):
            raise ValidationError('密码不符合')

        if not re.findall(r'^1[3-8]\d{9}$', mobile):
            raise ValidationError('请输入正确的手机号')

        return attrs
	# 重写create
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

写入视图

from rest_framework.viewsets import ModelViewSet
from users.models import User
# 分页
from rest_framework.pagination import PageNumberPagination

# 自定义分类
class Pageination(PageNumberPagination):
    page_size = 3
    max_page_size = 5
    page_query_param = 'page'
    page_size_query_param = 'pageSize'


# 用户信息
class UserInfoViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer
	# 调用分类
    pagination_class = Pageination

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)

        if ser.is_valid():
            ser.save()
            return Response({'code': 201, 'msg': '添加成功'}, status=201)
        return Response({'code': 400, 'smg': '添加失败'}, status=200)

写入路由

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('users', views.UserInfoViewSet)   
urlpatterns += router.urls
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值