美文网首页
drf基于APIView的五个接口+继承ModelSeriali

drf基于APIView的五个接口+继承ModelSeriali

作者: 晨颜 | 来源:发表于2023-05-18 20:25 被阅读0次

    view.py

    from django.shortcuts import render
    
    # Create your views here.
    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    from .serializer import PublishSerializer,AuthorSerializer,BookSerializer
    from . import models
    
    
    class BookView(APIView):
        print('BookView')
    
        def get(self, request):
            print('book,getall')
            books = models.Book.objects.all()
            print(books)
            ser = BookSerializer(instance=books, many=True)
            print(ser.data)
            return Response({'code': 100, 'msg': 'getallok', 'data': ser.data})
    
        def post(self, request):
            ser = BookSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'addok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    class BookDetailView(APIView):
        print('BookDetailView')
    
        def get(self, request, pk):
            print('getone')
            bookobj = models.Book.objects.get(pk=pk)
            print(bookobj)
            ser = BookSerializer(instance=bookobj, many=False)
            return Response({'code': 100, 'msg': 'getoneok', 'data': ser.data})
    
        def put(self, request, pk):
            bookobj = models.Book.objects.get(pk=pk)
            print('putputputputbookbookbook',bookobj)
            ser = BookSerializer(instance=bookobj, data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'putok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    
        def delete(self, request, pk):
            models.Book.objects.filter(pk=pk).delete()
    class PublishView(APIView):
        print('PublishVIew')
    
        def get(self, request):
            Publishs = models.Publish.objects.all()
            ser = PublishSerializer(instance=Publishs, many=True)
            return Response({'code': 100, 'msg': 'getallok', 'data': ser.data})
    
        def post(self, request):
            ser = PublishSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'addok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    class PublishDetailView(APIView):
        print('PublishDetailView')
    
        def get(self, request, pk):
            print('getone')
            Publishobj = models.Publish.objects.get(pk=pk)
            print(Publishobj)
            ser = PublishSerializer(instance=Publishobj, many=False)
            return Response({'code': 100, 'msg': 'getoneok', 'data': ser.data})
    
        def put(self, request, pk):
            Publishobj = models.Publish.objects.get(pk=pk)
            ser = PublishSerializer(instance=Publishobj, data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'putok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    
        def delete(self, request, pk):
            models.Publish.objects.filter(pk=pk).delete()
    
    class AuthorView(APIView):
        print('AuthorView')
    
        def get(self, request):
            Authors = models.Author.objects.all()
            ser = AuthorSerializer(instance=Authors, many=True)
            return Response({'code': 100, 'msg': 'getallok', 'data': ser.data})
    
        def post(self, request):
            ser = AuthorSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'addok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    class AuthorDetailView(APIView):
        print('AuthorDetailView')
    
        def get(self, request, pk):
            print('getone')
            Authorobj = models.Author.objects.get(pk=pk)
            print(Authorobj)
            ser = AuthorSerializer(instance=Authorobj, many=False)
            return Response({'code': 100, 'msg': 'getoneok', 'data': ser.data})
    
        def put(self, request, pk):
            Authorobj = models.Author.objects.get(pk=pk)
            ser = AuthorSerializer(instance=Authorobj, data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 100, 'msg': 'putok', 'data': request.data})
            return Response({'code': 101, 'msg': ser.errors})
    
        def delete(self, request, pk):
            Authorobj = models.Author.objects.get(pk=pk)
            models.AuthorDetail.objects.filter(pk=Authorobj.pk).delete()
            Authorobj.delete()
            return Response({'code': 100, 'msg': 'delok', 'data': pk})
    

    serializer.py

    from rest_framework import serializers
    from rest_framework.serializers import ModelSerializer
    from . import models
    
    
    class BookSerializer(ModelSerializer):
        print('BookSerializier')
    
        class Meta:
            model = models.Book
            fields = ['name', 'price', 'publish_detail', 'author_list', 'publish', 'author']
            extra_kwargs = {
                'name': {'max_length': 10, 'min_length': 2, 'required': True},
                'publish': {'write_only': True},
                'author': {'write_only': True}
            }
    
        publish_detail = serializers.DictField(read_only=True)
        author_list = serializers.ListField(read_only=True)
    
    
    class PublishSerializer(ModelSerializer):
    
        print('PublishSerializer')
    
        class Meta:
            model = models.Publish
            fields = '__all__'
    
    
    class AuthorSerializer(ModelSerializer):
        print('AuthorSerializer')
        class Meta:
            model = models.Author
            fields = ['name', 'phone', 'authordetail', 'book_list','age','email']#
            extra_kwargs = {
                'name': {'max_length': 10, 'min_length': 2, 'required': True},
            }
    
        book_list=serializers.ListField(read_only=True)
        authordetail = serializers.DictField(read_only=True)
        age=serializers.IntegerField(source='author_detail.age')###重点看
        email=serializers.CharField(source='author_detail.email')###重点看
        def create(self, validated_data):
            print(validated_data)
            detail_dict=validated_data.pop('author_detail')###重点看
            author_obj_detail=models.AuthorDetail.objects.create(**detail_dict)###重点看
            validated_data['author_detail_id']=author_obj_detail.pk###重点看,其中注意author_detail_id要与表字段名对应
            print(validated_data)
            author_obj=models.Author.objects.create(**validated_data)
            print(author_obj)
            return author_obj
        def update(self, instance, validated_data):
            print(instance)
            print(validated_data)
            return instance
    

    modles.py

    from django.db import models
    
    
    # Create your models here.
    class Book(models.Model):
        name = models.CharField(max_length=32)
        price = models.CharField(max_length=10)
        publish = models.ForeignKey(to='Publish', on_delete=models.SET_NULL, null=True)
        author = models.ManyToManyField(to='Author')
    
        @property
        def publish_detail(self):
            return {'id': self.publish.pk, 'name': self.publish.name, 'addr': self.publish.addr}
    
        # @property
        def author_list(self):
            l = []
            for author in self.author.all():
                print(author)
                l.append({'id': author.pk, 'name': author.name, 'phone': author.phone, 'age': author.author_detail.age})
            print(l)
            return l
    
    
    class Publish(models.Model):
        name = models.CharField(max_length=32)
        addr = models.CharField(max_length=32)
    
    
    class Author(models.Model):
        name = models.CharField(max_length=32)
        phone = models.CharField(max_length=11)
        author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
    
        @property
        def authordetail(self):
            return {'email': self.author_detail.email, 'age': self.author_detail.age}
    
        # @property
        def book_list(self):
            l = []
            for book in self.book_set.all():
                l.append({'id': book.pk, 'price': book.price, 'publish': book.publish.name})
            return l
    
    
    class AuthorDetail(models.Model):
        email = models.EmailField()
        age = models.SmallIntegerField()
    

    相关文章

      网友评论

          本文标题:drf基于APIView的五个接口+继承ModelSeriali

          本文链接:https://www.haomeiwen.com/subject/kyhgsdtx.html