9.22学习的APIView底层序列化走向以及复习view和最简单的增删改查from rest_framework.viewsets import ModelViewSet
作者:互联网
from rest_framework import serializers from .models import * from rest_framework.serializers import ModelSerializer class Teacherser(ModelSerializer): class Meta: model = Teacher fields = '__all__' class Teacherapisrr(serializers.Serializer): name = serializers.CharField(max_length=20) classrome = serializers.CharField(max_length=20) def create(self, validated_data): return Teacher.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name') instance.classrome = validated_data.get('classrome') instance.save() return instance
# APIView class Teacherapi(APIView): def post(self, request): data = request.data data = Teacherapisrr(data=data) if data.is_valid(): data.save() return Response({'code':200}) def put(self,request): data00=request.data id=request.GET.get('id') data1=Teacher.objects.filter(id=id).first() data2=Teacherapisrr(instance=data1,data=data00) if data2.is_valid(): print(1111111111111111) data2.save() return HttpResponse({'code':200})
# View class ViewTeacher(View): def get(self, request): data = Teacher.objects.all() print(data) list = [] for i in data: dict={} dict['名称']=i.name dict['班级']=i.classrome list.append(dict) print(list) return HttpResponse(list) def post(self, request): Teacher.objects.create(name='zhangsan', classrome='老缪朱') return HttpResponse({'code': 200}) def put(self, request): name = request.GET.get('name') classrome = request.GET.get('classrome') id = request.GET.get('id') data = Teacher.objects.filter(id=id) print(data) for i in data: i.name = name i.classrome = classrome i.save() return HttpResponse({'code': 200}) def delete(self, request): id = request.GET.get('id') Teacher.objects.filter(id=id).delete() return HttpResponse({'code': 200})
# Modelviewset class San(ModelViewSet): queryset = Teacher.objects.all() serializer_class = Teacherser
注::::: url modelviewset
from rest_framework.routers import DefaultRouter router = DefaultRouter() #引用 router.register('路由名',View名) path('', include(router.urls))#使用include引出url
标签:9.22,return,name,classrome,request,改查,序列化,data,id 来源: https://blog.csdn.net/weixin_57253143/article/details/120420694