zoukankan      html  css  js  c++  java
  • drfday6

    作业:

    1 一个表可不可以有多个自增字段

    不可以

    1594646964(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)
    
    

    数据:

    image-20200714012100863

    2.1 查:

    查所有:

    image-20200714012156644

    查单个:

    image-20200714012248049

    2.2 改

    改单个:

    image-20200714013105632

    改多个:

    image-20200714015802486

    2.3 新增

    新增一个:

    image-20200714020014461

    新增多个:

  • 相关阅读:
    AFNetworking 3.0 源码解读(四)之 AFURLResponseSerialization
    AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization
    url 编码(percentcode 百分号编码)(转载)
    AFNetworking 3.0 源码解读(二)之 AFSecurityPolicy
    使用UICollectionView实现首页的滚动效果
    AFNetworking 3.0 源码解读(一)之 AFNetworkReachabilityManager
    c 线程(平行世界)
    ZFPlayer 源码解读
    ios 音视频实现边播边缓存的思路和解决方案 (转)
    c 网络与套接字socket
  • 原文地址:https://www.cnblogs.com/cainiaoqianxun/p/13296906.html
Copyright © 2011-2022 走看看