• day 82 Serializer类进阶三【ModelSerializer】


    media 配置:

      项目setting.py

        MEDIA_URL = '/media/'
        MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

      路由:

         urlpatterns = [
       url(r'^media/(?P<path>.*)', serve, {'document_root':settings.MEDIA_ROOT}),]

    结论:

    1.插拔字段,省去了views中的跨表查, 插拔式默认read_only
    2.ModelSerializer有Updata和create, 若没有特殊业务要求,可以不需要重写
    3.
    extra_kwargs中:不想展现给前台【显示】-- "write_only": True
            必须要传参 --- "required":True


    moderserializer.py:
    from rest_framework import serializers
    
    from app6 import models
    
    
    class BookModelSerializer(serializers.ModelSerializer):
    
        # 如果fields为[]自定义方式,必须需要将owen加入到自定义字段中,否则报错
        # 另一种方式,迁移到model类中定义为property--- 建议使用【插拔式】
        # owen = serializers.SerializerMethodField()
        # def get_owen(self, obj):
        #     print(type(obj),obj)   #<class 'app6.models.Book'> 书一
        #     return "xx"             #  <class 'app6.models.Book'> 书二
    
    
        class Meta:
            model = models.Book
            # fields = '__all__'  # 提供该表所有字段,不包含插拔字段
            # depth = 1   # 自动深度
            # exclude =['create_time', 'id', 'is_delete']  #不显示这些字段,不包含插拔式字段
            fields = ['name', 'price','publish','authors','publish_name','authors_list', 'authors_detail_list']  # 自定义字段 --  可以插拔字段, 插拔字段只参与系列化
    
    
            # extra_kwargs中:不想展现给前台【显示】-- "write_only": True
            #                    必须要传参 ---  "required":True
            extra_kwargs = {
                'publish':{
                    'write_only':True,
                },
                'authors':{
                    'write_only':True
                },
                'price':{
                    'write_only':True,  # 不会显示
                    'required': True,
                    'error_messages':{
                        'required':'price不能为空'
                    }
                }
            }
    
    
    
        # ModelSerializer有Updata和create, 若没有特殊业务要求,可以不需要重写
        def create(self, validated_data):
            authors_list = validated_data.pop('authors')
            obj = models.Book.objects.create(**validated_data)
            obj.authors.add(*authors_list)
            return obj
    
    class AuthorModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Author
            fields = ['name', 'icon','price']
    
        def create(self, validated_data):
            return models.Author.objects.create(**validated_data)
    
    class PublishModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Publish
            fields = ("name", "address", "phone")
            extra_kwargs ={
                "name":{
                    "max_length": 6,
                    "min_length": 3,
                    "error_messages":{
                    "max_length": "姓名最长6位",
                    "min_length": "姓名最短3位",
                    },
                },
                "phone":{
                     "max_length": 11,
                     "min_length": 8,
                    "error_messages":{
                        "max_length":"电话最大11位",
                        "min_length": "电话最小8位",
                    }
                },
                "address":{
                    # "write_only":True,
                }
            }
    View Code
    
    

    urls.py
      # 一级路由
     url(r'^app7/', include('app7.urls')),
    
    
    # 二级路由
    urlpatterns = [
        url(r'^books/$', views.Books.as_view()),
        url(r'^books/(?P<pk>d+)/$', views.Books.as_view()),
        url(r'^authors/$', views.Authors.as_view()),
        url(r'^authors/(?P<pk>d+)/$', views.Authors.as_view()),
        url(r'^publishes/$', views.Publishes.as_view()),
        url(r'^Publishes/(?P<pk>d+)/$', views.Publishes.as_view()),
    ]
    View Code
    
    


    views.py 【含认证类】
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from app6 import models
    from app6.modelserializer import BookModelSerializer, AuthorModelSerializer, PublishModelSerializer
    # Create your views here.
    
    # 自定义一个认证类
    class MyAuth():
        def authenticate(self,request):
            print("我是认证类>>>>")
    
    class Books(APIView):
        authentication_classes = [MyAuth,]
        def get(self,request,*args,**kwargs):
            if kwargs.get('pk'):
                query_list = models.Book.objects.filter(pk=kwargs.get('pk'))
            else:
                query_list = models.Book.objects.all()
            query_data_dic = BookModelSerializer(instance=query_list, many=True).data
            return Response({
                'status':0,
                'msg':"get ok",
                'results':query_data_dic
            })
    
        def post(self,request, *args,**kwargs):
            query_ser = BookModelSerializer(data=request.data)
            if query_ser.is_valid():
                finshi_obj = query_ser.save()
                back_dic = {
                    "status":0,
                    "msg":"post ok",
                    "result": BookModelSerializer(instance=finshi_obj).data
                    }
            else:
                back_dic = {
                    "status":1,
                    "msg":"failed",
                    "result":query_ser.errors,
                }
            return Response(back_dic)
    
        def put(self,request, *args, **kwargs):
            pk = kwargs.get('pk')
            query_obj = models.Book.objects.filter(pk=pk).first()
            query_set = BookModelSerializer(instance=query_obj, data=request.data)
            if query_set.is_valid():
                ser_obj = query_set.save()
                back_dic = {
                    "status":0,
                    "msg":"put ok",
                    # "result": query_set.validated_data
                }
            else:
                back_dic = {
                    "status": 1,
                    "msg": "failed",
                    "result": query_set.errors}
    
            return  Response(back_dic)
    
    class Authors(APIView):
        def get(self, request,*args,**kwargs):
            if kwargs.get('pk'):
                query_list = models.Author.objects.filter(pk=kwargs.get('pk'), is_delete=False)
            else:
                query_list = models.Author.objects.filter(is_delete=False)
            query_ser = AuthorModelSerializer(instance=query_list, many=True).data
            if query_ser:
                back_dic = {
                    'status':0,
                    'msg':"get ok",
                    'result': query_ser
                }
            else:
                back_dic = {
                    'status': 1,
                    'msg': "failed",
                }
            return  Response(back_dic)
    
        def post(self,request, *args, **kwargs):
            query_data = AuthorModelSerializer(data=request.data)
            if query_data.is_valid():
                obj = query_data.save()
                back_dic = {
                    "status": 0,
                    "msg": "post ok",
                    "result": AuthorModelSerializer(instance=obj).data}
            else:
                back_dic = {
                    "status":1,
                    "msg":"post failed",
                    "result": []
                }
            return Response(back_dic)
    
    class Publishes(APIView):
        def get(self, request, *args, **kwargs):
            query_list  = models.Publish.objects.filter(is_delete=False)
            query_ser = PublishModelSerializer(instance=query_list, many=True)
            back_dic = {
                "status":0,
                "msg":"get publishes ok",
                "result": query_ser.data
            }
            return Response(back_dic)
    
        def post(self,request, *args, **kwargs):
            query_ser = PublishModelSerializer(data=request.data)
            if query_ser.is_valid():
                new_obj = query_ser.save()
                print(new_obj)
                back_dic = {
                    "status":0,
                    "msg":"publish post ok"
                }
            else:
                back_dic = {
                    "status": 1,
                    "msg": "publish post failed",
                    "result":query_ser.errors
                }
            return  Response(back_dic)
    View Code
    
    
    






  • 相关阅读:
    好用的QT连接
    c指针点滴-指针与类型
    c指针点滴5-指针变量计算
    c指针点滴4-指针的值
    c指针点滴三(指针运算)
    c语言指针点滴1
    c指针点滴2之比大小
    c指针点滴1
    linux安装redis
    支付宝支付接口流程
  • 原文地址:https://www.cnblogs.com/qingqinxu/p/11373350.html
Copyright © 2020-2023  润新知