序列化器代码:
from rest_framework import serializers
from myapp.models import People
class PeopleSerializer(serializers.Serializer):
name = serializers.CharField(max_length=20)
sex = serializers.CharField(max_length=20)
money = serializers.IntegerField()
ranking = serializers.IntegerField()
def create(self, validated_data):
res = People.objects.create(
**validated_data
)
return res
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
instance.sex = validated_data.get('sex')
instance.money = validated_data.get('money')
instance.ranking = validated_data.get('ranking')
instance.save()
return instance
class PeopleSerializer2(serializers.ModelSerializer):
class Meta:
model = People
fields = '__all__'
类试图代码:
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import People
from myapp.serializers import PeopleSerializer,PeopleSerializer2
class MyView(APIView):
def get(self,request):
print(request.query_params)
return Response({'msg':'success'},status=200)
def post(self,request):
print(request.data)
return Response({'msg':'success'},status=201)
class PeopleView(APIView):
def get(self,request):
people = People.objects.all()
ser = PeopleSerializer2(people,many=True)
return Response(ser.data,status=200)
def post(self,request):
ser = PeopleSerializer2(data=request.data)
if ser.is_valid(raise_exception=True):
ser.save()
return Response({"msg":"添加数据成功"},status=201)
return Response({"msg":"添加数据失败"})
class PeopleView2(APIView):
def get(self, request, id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
return Response({'msg':'查询失败'},status=404)
ser = PeopleSerializer2(peo_data)
return Response(ser.data,status=200)
def put(self,request,id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
return Response({'msg':'查询失败'},status=404)
ser = PeopleSerializer2(instance=peo_data,data=request.data)
if ser.is_valid(raise_exception=True):
ser.save()
return Response({"msg": "修改数据成功"}, status=201)
return Response({"msg": "修改数据失败"})
def delete(self,request,id):
try:
People.objects.get(id=id).delete()
except Exception as e:
print(e)
return Response({'msg': '删除失败'}, status=404)
return Response({'msg': '删除成功'}, status=204)