作业:
1 一个表可不可以有多个自增字段
不可以
2 用GenericAPIView重写book的单增,群增,。。。。
路由:
from django.urls import path, re_path
from app01.views import BookView
urlpatterns = [
re_path('books/(?P<pk>\d+)', BookView.as_view()),
path('books/', BookView.as_view()),
]
视图:
from rest_framework.generics import GenericAPIView
from app01.models import Book
from app01.ser import BookModelSerializer
from rest_framework.response import Response
# Create your views here.
class BookView(GenericAPIView):
queryset = Book.objects
serializer_class = BookModelSerializer
def get(self, request, *args, **kwargs):
if kwargs.get('pk', None):
book = self.get_queryset().filter(is_delete=False).filter(pk=kwargs.get('pk'))
book_ser = self.get_serializer(book, many=True)
return Response(book_ser.data)
book_list = self.get_queryset().filter(is_delete=False)
book_list_ser = self.get_serializer(book_list, many=True)
return Response(book_list_ser.data)
def post(self, request, *args, **kwargs):
if isinstance(request.data, dict):
book_ser = self.get_serializer(data=request.data, partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
elif isinstance(request.data, list):
book_ser = self.get_serializer(data=request.data, many=True)
print(type(book_ser))
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
def put(self, request, *args, **kwargs):
if kwargs.get('pk', None):
book = self.get_queryset().filter(pk=kwargs.get('pk')).first()
book_ser = self.get_serializer(instance=book, data=request.data, partial=True)
book_ser.is_valid()
book_ser.save()
return Response(data=book_ser.data)
else:
book_list = []
modify_data = []
for item in request.data:
pk = item.pop('id')
book = Book.objects.filter(pk=pk).first()
book_list.append(book)
modify_data.append(item)
book_ser = self.get_serializer(instance=book_list, data=modify_data, many=True, partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
pks = []
if pk:
pks.append(pk)
else:
pks = request.data.get('pks')
ret = self.get_queryset().filter(pk__in=pks, is_delete=False).update(is_delete=True)
if ret:
return Response({'msg': '删除成功'})
else:
return Response(data={'msg': '没有要删除的数据'})
自定义序列化器ser.py文件:
from rest_framework.serializers import ModelSerializer, ListSerializer
from app01.models import Book
class BookListSerializer(ListSerializer):
def update(self, instance, validated_data):
return [self.child.update(instance[i], attrs) for i, attrs in enumerate(validated_data)]
class BookModelSerializer(ModelSerializer):
class Meta:
list_serializer_class = BookListSerializer
model = Book
fields = ('id', 'title', 'price', 'author', 'publish')
extra_kwargs = {
'id': {'read_only': True}
}
模型表models.py:
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=31)
price = models.DecimalField(max_digits=8,decimal_places=2)
author = models.CharField(max_length=32)
publish = models.CharField(max_length=32)
is_delete = models.BooleanField(default=False)
数据:
2.1 查:
查所有:
查单个:
2.2 改
改单个:
改多个:
2.3 新增
新增一个:
新增多个: