-
serializer.py中的代码
from rest_framework import serializers from .models import * class UserSerializers(serializers.Serializer): username = serializers.CharField(max_length=64) age = serializers.IntegerField(allow_null=True) home = serializers.CharField(max_length=64) def create(self, validated_data): return User.object.create(**validated_data) def update(self, instance, validated_data): # instance 数据库里的模型 # validated_data 传进来要修改的数据 instance.username = validated_data.get('username', instance.username) instance.age = validated_data.get('age', instance.age) instance.home = validated_data.get('home', instance.home) instance.save() return instance
-
views.py中的代码
# 用户接口 class UserView(APIView): # 查看 def get(self, request): users = User.objects.all() ser = UserSerializer(users, many=True) data = ser.data return Response(data) # 添加 def post(self, request): data = request.data ser = UserSerializer(data=data) if ser.is_valid(): ser.save() return Response({'msg': '添加成功', 'code': 200}) else: print(ser.errors) # 修改 def put(self, request): data = request.data user = User.objects.get(id=1) ser = UserSerializer(user, data=data) if ser.is_valid(): ser.save() return Response({'msg': '修改成功', 'code': 200}) else: print(ser.errors) # 删除 def delete(self, request): uid = request.data.get('id') user = User.objects.filter(pk=uid).first() if user: user.delete() return Response({'msg': '删除成功', 'code': 200}) else: print(user.errors)