码迷,mamicode.com
首页 > 其他好文 > 详细

day 95 RestFramework序列化组件

时间:2018-06-21 01:40:43      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:field   pen   views   file   ons   mod   work   rom   src   

一 、复习

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请求). 

 

 

day 95 RestFramework序列化组件

标签:field   pen   views   file   ons   mod   work   rom   src   

原文地址:https://www.cnblogs.com/mengbin0546/p/9206679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!