Apiview使用方法
1.user/models.py 表数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): phone = models.CharField('手机号',max_length=20) img = models.ImageField(upload_to='user',null=True) nick_name = models.CharField('昵称',max_length=20) address = models.CharField('地址',max_length=255) class Meta: db_table = 'tb_user'
2.user/serializers.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework import serializers from user.models import User class UserInfoSerializer(serializers.Serializer): id = serializers.CharField(read_only=True)# 普通字段,设置id为只读字段,不能修改 username = serializers.CharField(min_length=3,max_length=20,error_messages= {'required': '该字段必填'})# 显示普通字段 img = serializers.ImageField(required=False) nick_name = serializers.CharField(max_length=20) address = serializers.CharField(max_length=255) xxx = serializers.SerializerMethodField(read_only=True)# 自定义显示(显示多对 aaa=serializers.SerializerMethodField(read_only=True) class Meta: model=User #展示自定义字段 def get_xxx(self,row): users=row.phone return users def get_aaa(self,r): nick=r.nick_name return nick #添加字段 def create(self, validated_data): return User.objects.create(**validated_data) #修改字段 def update(self,instance,validated_data): if validated_data.get('nick_name','address'): instance.address=validated_data['address'] instance.nick_name = validated_data['nick_name'] instance.save() return instance #权限 def validate_username(self,value): if value=='root': raise serializers.ValidationError('不能创建root管理员账号') return value def validate(self,attrs): print(attrs) if attrs.get("username")=='admin': raise serializers.ValidationError('不能创建admin用户') return attrs
3.user/views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from .serializers import UserInfoSerializer from rest_framework.views import APIView from .models import User class UserInfoViewSet(APIView): #查询用户 def get(self,request,*args,**kwargs): obj=User.objects.all() ser=UserInfoSerializer(obj,many=True) return Response(ser.data,status=200) #创建用户 def post(self,request): ser=UserInfoSerializer(data=request.data) #判断提交数据是否合法 if ser.is_valid(): ser.save() return Response(ser.data,status=201) return Response(ser.errors,status=400) #更改用户信息 def put(self,request): pk=request.query_params.get('pk') print(pk) try: userinfo=User.objects.get(id=pk) except Exception as e: return Response(data='用户不存在',status=201) ser=UserInfoSerializer(userinfo,data=request.data) if ser.is_valid(): ser.save() return Response(ser.data,status=201) return Response(data=ser.errors,status=400)
4.user/urls.py 路由
urlpatterns = [ path('apiview/', views.UserInfoViewSet.as_view()), ]
查询
http://192.168.56.100:8888/user/apiview/
修改
http://192.168.56.100:8888/user/apiview/?pk=5
添加
http://192.168.56.100:8888/user/apiview/