定义模型类
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
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
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