1

day 94 RestFramework序列化组件与视图view

一 、复习

1. CBV流程

class BookView(View):

     def get():
         pass
     def post():
         pass     

#url(r'^books/', views.BookView.as_view()),
#url(r'^books/', View.as_view()),
#url(r'^books/', View.view),
一旦用户访问books:
View.view(request)==View.dispatch(request)==self.get(request)

 

 

2.Restframework下的APIView流程

 

class BookView(APIView(View)):

     def get():
	     pass
     def post():
         pass
		 
#url(r'^books/', views.BookView.as_view()),
#url(r'^books/', APIView.as_view()),
#url(r'^books/', View.view),

一旦用户访问books:

View.view(request)==APIView.dispatch(request)====self.get(request)

3 新的request对象

  def APIView.dispatch(request):
        request = self.initialize_request(request, *args, **kwargs)
		request._request.GET 
		request._request.POST
		request.POST
		request.GET
		request.data(针对post请求,put/patch)
		

  

3.序列化组件

 

from rest_framework import serializers

class BookSerializers(serializers.Serializer):
    title=serializers.CharField(max_length=32)
    price=serializers.DecimalField(max_digits=8,decimal_places=2)
    publish=serializers.CharField(max_length=32,source="publish.name")
    #authors=serializers.CharField(max_length=32,source="authors.all")
    authors=serializers.SerializerMethodField()
    def get_authors(self,obj):
        temp=[]
        for obj in  obj.authors.all():
            temp.append(obj.name)
        return temp


        '''
        bs=BookSerializers(book_list,many=True)
        temp=[]
        for obj in book_list:

            temp.append({
                  'title':obj.title,
                  'price':obj.price,
                  'publish':obj.publish.name,
                  'authors':
            })

        bs.data=json.dumps(temp)


        '''


class BookView(APIView):

    def get(self,request):
        
        book_list=Book.objects.all() 
        bs=BookSerializers(book_list,many=True) # [{},{},{}]
        bs1=BookSerializers(model_obj)      # {}

        return Response(bs1.data)

    def post(self, request):

        print("request.data",request.data)
        print("request.data",request.data["title"])
        print("request.POST",request.POST)

        return HttpResponse("post.....")
    
    
    

 

 

 

 

 二 、 RestFramwork之序列化组件1(get请求) .    

 

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
from django.views import View
from app01.models import Book
import json

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import  serializers

"""
有了modelSerializer后以下的代码都没用啦 。 
from rest_framework import  serializers

class BookSerializers(serializers.Serializer):
    title =serializers.CharField(max_length=32)
    price =serializers.DecimalField(max_digits=8,decimal_places=2)
    publish =serializers.CharField(max_length=32,source="publish.Email")
    # authors =serializers.CharField(max_length=32,source="authors.all")
    authors =serializers.SerializerMethodField()
    def get_authors(self,obj):
        temp =[]
        for obj in obj.authors.all():
            temp.append(obj.name)
        return temp

"""


""" 
#总结的源码
        bs =BookSerializers(book_list,many=True)
        temp=[]
        for obj in book_list:
            temp.append({
                ’titlte':obj.title,
                ’price':obj.price,
                ’publish':obj.publish.name,
                'authors':obj.authors.
            
            })
#总结的源码            
            
        bs.data =json.dumps(temp)
"""

from rest_framework.serializers import ModelSerializer
class BookModelSerializers(ModelSerializer):
    class Meta:
        model =Book
        fileds ="__all__"
        authors =serializers.SerializerMethodField()
            def get_authors(self,obj):
                temp =[]
                for obj in obj.authors.all():
                    temp.append(obj.name)
                return temp

class BookView(APIView):
    """
    get请求:获取所有的书籍
    post请求:添加一本书籍
    """
    def get(self,request):
        book_list =Book.objects.all()
        bs =BookModelSerializers(book_list,many= True)

        return Response(bs.data)

    """
    def get(self,request):
        print(request._request.GET)
        print(request.GET)
        print(request.query_params)
    
        book_list= Book.objects.all()
        # 方式一:
        temp=[]
        from django.forms.models import model_to_dict
        # for book in book_list:
        #     temp.append(model_to_dict(book)) #序列化方式一 django提供的.
    
        #方式二:
        # from django.core.serializers import serialize
        # data =serialize("json",book_list)  #序列化方式二 django提供的.
        # return Response(data)
    
        #方式三:
        bs =BookSerializers(book_list,many=True)
        print("bs:is",bs)
    
        return  Response(bs.data)
    """

class BookDetailView(View):
    pass

以上代码有问题打印不出来 publish 和author字段的内容.

 

 

 

三、RestFramwork之序列化组件2(POST请求 添加数据). 

 查看红颜色部分为post请求

from rest_framework.serializers import ModelSerializer
class BookModelSerializers(ModelSerializer):
    class Meta:
        model =Book
        fields ="__all__"
        authors =serializers.SerializerMethodField()
        def get_authors(self,row):
            temp =[]
            for i in row.authors.all():
                print(i.name)
                temp.append({'id':i.id,'name':i.name})
            return temp
class BookView(APIView):
    """
    get请求:获取所有的书籍
    post请求:添加一本书籍
    """
    def get(self,request):
        book_list =Book.objects.all()
        bs =BookModelSerializers(instance=book_list,many= True)
        print(bs.data)
        return Response(bs.data)
def post(self,request): bs =BookModelSerializers(data=request.data) if bs.is_valid(): #校验字段接口 obj =bs.save() #创建记录接口create return Response(bs.data) #序列化接口 return Response(bs.error)#序列化接口

  

 

 

 

三、RestFramwork之序列化组件3(GET请求 查询某一本书籍数据). 

 views文件






class BookDetailView(APIView): """ 查询某一本书籍 """ def get(self,request,id): book =Book.objects.filter(pk=id).first() print(id) bs = BookModelSerializers(book) print("bs.dataaaaa",bs.data) return Response(bs.data)

  

url

from django.conf.urls import url
from django.contrib import admin

from app01 import  views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/$',views.BookView.as_view()),
    url(r"^books/(\d+)/$",views.BookDetailView.as_view())  
注意$符号必须加上,否则会出错
]

 

 

 

三、RestFramwork之序列化组件4(PUT请求 修改某一本书籍数据). 

 

 

class BookDetailView(APIView):
    """
    查询某一本书籍
    """
    def get(self,request,id):
        book =Book.objects.filter(pk=id).first()
        print(id)
        bs = BookModelSerializers(book)
        print("bs.dataaaaa",bs.data)
        return  Response(bs.data)


  """
  修改某一本书籍
  """
def put(self,request,id): book
=Book.objects.filter(pk=id).first() print(request.data) bs = BookModelSerializers(data=request.data,instance=book) if bs.is_valid(): bs.save()# book.update(request.data) return Response(bs.data) else: return Response(bs.errors)

 

四、RestFramwork之序列化组件5(delete请求 删除某一本书籍数据). 

 

class BookView(APIView):
    """
    get请求:获取所有的书籍
    post请求:添加一本书籍
    """
    def get(self,request):
        book_list =Book.objects.all()
        bs =BookModelSerializers(instance=book_list,many= True)
        return Response(bs.data)
    def post(self,request):
        bs =BookModelSerializers(data=request.data)
        if bs.is_valid():  #校验字段接口
            obj =bs.save() #创建记录接口create
            return Response(bs.data)  #序列化接口
        return Response(bs.error)#序列化接口

class BookDetailView(APIView):
    """
    查询某一本书籍
    """
    def get(self,request,id):
        book =Book.objects.filter(pk=id).first()
        print(id)
        bs = BookModelSerializers(book)
        print("bs.dataaaaa",bs.data)
        return  Response(bs.data)

    """
    修改某一本书籍
    """
    def put(self,request,id):
        book =Book.objects.filter(pk=id).first()
        print(request.data)

        bs = BookModelSerializers(data=request.data,instance=book)
        if bs.is_valid():
            bs.save()# book.update(request.data)

            return Response(bs.data)

        else:
            return Response(bs.errors)

    """
    删除某一本书籍
    """
    def delete(self,request,id):
        Book.objects.filter(pk=id).first().delete()
        return Response()

 

 

from app01.models import Publish,Author
class PublishModelSerializers(ModelSerializer):
    class Meta:
        model =Publish
        fields ="__all__"

class PublishView(APIView):
    """
    publishs  : get请求 :获取所有的出版社
                post请求:获取一个出版社
    """
    def  get(self,request): #查询所有数据
        publish_list =Publish.objects.all()
        bs =PublishModelSerializers(publish_list,many=True)
        return  Response(bs.data)#序列化接口

    def post(self,request): #添加一条数据
        bs =PublishModelSerializers(data=request.data)
        if bs.is_valid():#校验字段接口
            obj=bs.save()#创建记录接口create

            return Response(bs.data)#序列化接口

        return Response(bs.errors)#序列化接口


class PublishDetailView(APIView):
    def get(self,request,id): #查询一条数据
        publish =Publish.objects.filter(pk=id).first()
        bs =PublishModelSerializers(publish)
        return Response(bs.data)
    def put(self,request,id): #修改一条数据
        publish =Publish.objects.filter(pk=id).first()
        bs =PublishModelSerializers(data=request.data,instance=publish)
        if bs.is_valid():
            bs.save()# publish.update(request.data)
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def delete(self,request,id): #删除一条数据
        Publish.objects.filter(pk=id).delete()
        return Response()

(序列化结束)

 

五、RestFramwork之视图

 视图函数进行封装 ,book 模型序列化,publish模型序列化 。。。。可以给他们进行封装所以引出了视图混合类(maxins)。

 

第一种封装 maxin 混合类

 

url文件 (红色部分)

from django.conf.urls import url
from django.contrib import admin

from app01 import  views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/$', views.BookView.as_view()),
    url(r"^books/(\d+)/$", views.BookDetailView.as_view()),

    #mixin增删改查方式使用的
    url(r"^publishes/$", views.PublishView.as_view()),
    url(r'^publishes/(\d+)/$', views.PublishDetailView.as_view()),


    url(r'^authors/$', views.AuthorsModelView.as_view({"get": "list", "post": "create"}), ),
    url(r'^authors/(?P<pk>\d+)/$', views.AuthorsModelView.as_view({
        'get': 'retrieve',
        'put': 'update',
        'delete': 'destroy'
    }), ),

 

 

view文件

#通过mixins的第一种方式 查询增删改查#######################mixins#################################

from rest_framework import generics
from rest_framework import mixins

class PublishModelSerializers(ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"

class PublishView(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
    queryset=Publish.objects.all()
    serializer_class =PublishModelSerializers
    def get(self,request,*args,**kwargs):
        return  self.list(self,request,*args,**kwargs)

    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)


class PublishDetailView(mixins.UpdateModelMixin,
                        mixins.RetrieveModelMixin,
                        mixins.DestroyModelMixin,
                        generics.GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishModelSerializers

    def get(self, request, *args, **kwargs):
        return self.retrieve(self, request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request,*args,**kwargs)

    def delete(self, request, *args,**kwargs):
        return self.destroy(request,*args,**kwargs)

 

以上增删改查有点问题

 

 

第二种封装方式 (generic)

url

from django.conf.urls import url
from django.contrib import admin

from app01 import  views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^books/$', views.BookView.as_view()),
    # url(r"^books/(\d+)/$", views.BookDetailView.as_view()),

    #第一种查询方式
    # url(r"^publishes/$", views.PublishView.as_view()),
    # url(r'^publishes/(\d+)/$', views.PublishDetailView.as_view()),


    #第二种查询方式
    url(r"^publishes/$", views.PublishViewSet.as_view()),
    url(r'^publishes/(\d+)/$', views.PublishDetailViewSet.as_view()),


    #第三种查询方式(modelviewset)
    # url(r'^authors/$', views.AuthorsModelView.as_view({"get": "list", "post": "create"}), ),
    # url(r'^authors/(?P<pk>\d+)/$', views.AuthorsModelView.as_view({
    #     'get': 'retrieve',
    #     'put': 'update',
    #     'delete': 'destroy'
    # }), ),


]

views

# 通过Generics类的第二种方式增删改查#######################mixins【viewset】#################################


from rest_framework import mixins
from rest_framework import generics

-----------------------------序列化操作----------------------------------
class BookModelSerializers(ModelSerializer): class Meta: model = Publish fields = "__all__" class PublishModelSerializers(ModelSerializer): class Meta: model = Publish fields = "__all__"

----------------------------增删改查------------------------------------ class BookViewSet(generics.ListCreateAPIView): #查看、增加 queryset = Book.objects.all() serializer_class = BookModelSerializers



class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView): #删除更新 queryset = Book.objects.all() serializer_class = BookModelSerializers



=====================================================================
class PublishViewSet(generics.ListCreateAPIView): queryset = Publish.objects.all() serializer_class = PublishModelSerializers class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView): queryset = Publish.objects.all() serializer_class = PublishModelSerializers

 

 

 

 

第三种封装(modelviewset)

url文件(红色部分)

 

from django.conf.urls import url
from django.contrib import admin

from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^books/$', views.BookView.as_view()),
# url(r"^books/(\d+)/$", views.BookDetailView.as_view()),

#第一种查询方式
# url(r"^publishes/$", views.PublishView.as_view()),
# url(r'^publishes/(\d+)/$', views.PublishDetailView.as_view()),


#第二种查询方式
url(r"^publishes/$", views.PublishViewSet.as_view()),
url(r'^publishes/(\d+)/$', views.PublishDetailViewSet.as_view()),


#第三种查询方式(modelviewset)
# url(r'^authors/$', views.AuthorsModelView.as_view({"get": "list", "post": "create"}), ),
# url(r'^authors/(?P<pk>\d+)/$', views.AuthorsModelView.as_view({
# 'get': 'retrieve',
# 'put': 'update',
# 'delete': 'destroy'
# }), ),

 

 

views逻辑部分

#通过mixins的第二种方式 查询增删改查(进一步优化)#######################mixins【viewset】#################################

from rest_framework.viewsets import ModelViewSet


class AuthorModelSerializers(ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"

class AuthorsModelView(ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

 

posted @ 2018-06-20 23:36  萌哥-爱学习  阅读(203)  评论(0编辑  收藏  举报