1. 程式人生 > >檢視元件程式碼

檢視元件程式碼

序列化器程式碼

# 宣告序列化器
from rest_framework import serializers
from djangoDome.models import Book

class PublisherSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)

class AuthorSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=32)


#自定義欄位
def my_validate(value):
if 'xxoo' in value.lower():
#拋敏感詞彙
raise serializers.ValidationError('敏感詞彙')
return value


# class BookSerializer(serializers.Serializer):
# id = serializers.IntegerField(required=False)
# title = serializers.CharField(max_length=32,)# 自定義的加這個引數 validators=[my_validate,]
# pub_time = serializers.DateField()
# category=serializers.CharField(source='get_category_display',read_only=True) #此處為多選時用
# #read_only = True 正序查詢
# publisher=PublisherSerializer(read_only=True) #多對一
# authors=AuthorSerializer(many=True,read_only=True) #多對多用 many=True
#
# #write_only =True 反序查詢 要重新定義
# post_category = serializers.IntegerField(write_only=True)
# publisher_id = serializers.IntegerField(write_only=True)
# author_list = serializers.ListField(write_only=True)
#
# #重寫 create 方法
# def create(self, validated_data):
# #validated_data 校驗通過的資料 就是book_obj
# # 通過ORM操作給Book表增加資料
# book_obj=Book.objects.create(title=validated_data['title'],
# pub_time=validated_data["pub_time"],
# category=validated_data["post_category"],
# publisher_id=validated_data["publisher_id"]
# )
# book_obj.authors.add(*validated_data['author_list'])
# return book_obj
#
# #重寫update 方法
# def update(self, instance, validated_data):
# # instance 更新的book_obj 物件
# # validated_data 校驗通過的資料
# # ORM做更新操作 對每個欄位進行更新
# instance.title=validated_data.get('title',instance.title)
# instance.pub_time = validated_data.get("pub_time", instance.pub_time)
# instance.category = validated_data.get("post_category", instance.category)
# instance.publisher_id = validated_data.get("publisher_id", instance.publisher_id)
# #此處是對多對多個欄位 進行查詢
# if validated_data.get("author_list"):
# #set 因為是列表多個數據
# instance.authors.set(validated_data["author_list"])
# #編輯一定要更新
# instance.save()
# return instance
#
# # 對單個值進行校驗
# def validate_title(self,value):
# # value就是title的值 對value處理
# if 'xxoo' not in value.lower():
# raise serializers.ValidationError('少東西了')
# return value
#
# #對所有欄位進行 校驗
# def validate(self, attrs):
# # attrs 字典有你傳過來的所有的欄位
# if 'xxoo' in attrs['title'].lower() and attrs["post_category"] == 1:
# return attrs
# else:
# raise serializers.ValidationError('分類或標題不合符要求')


class BookSerializer(serializers.ModelSerializer):

#對多選欄位,一對多,多對多欄位 進行重新定義 此處為序列化的時候顯示
category_display=serializers.SerializerMethodField(read_only=True)
publisher_info=serializers.SerializerMethodField(read_only=True)
authors_info=serializers.SerializerMethodField(read_only=True)
#多選查詢 obj 就是序列化的每個Book物件
def get_category_display(self,obj):
return obj.get_category_display()

#一對多查詢
def get_publisher_info(self,obj):
#找到查詢外來鍵的物件
publisher_obj=obj.publisher
#返回publisher表的內容
return {'id':publisher_obj.id,'title':publisher_obj.title}

#多對多的查詢
def get_authors_info(self,obj):
#找到所有的物件
authors_obj=obj.authors.all()
# 返回authors表的內容 推到式
return [{"id":i.id,'name':i.name}for i in authors_obj]

class Meta:
model=Book
fields='__all__'
# exclude=["id"]
# 會讓你這些所有的外來鍵關係變成read_only = True 最多4層 不建議用
# depth = 1

#相當於extra_kwargs={"預設的欄位名稱":{自定義的引數配置資訊}}
#用在反序列化 給表字段新增引數
extra_kwargs={'publisher':{'write_only':True},
"authors": {"write_only": True}}

檢視封裝程式碼
from django.shortcuts import render

from rest_framework.views import APIView #檢視
from djangoDome.models import Book
from rest_framework.response import Response #相等於django的render等
from SerDemo.serializers import BookSerializer
from rest_framework.viewsets import ViewSetMixin #重做as_view(),可以傳參,第三次封裝
from rest_framework import viewsets



# 封裝為公共的類 都能用
class GenericAPIView(APIView):
# 此處為面向物件的設定靜態變數一樣 預設為空對其進行操作
queryset = None # 查到表的物件
serializer_class = None # 序列器

#定義方法 來取值
def get_queryset(self):
return self.queryset.all()#此處用all()為資料在快取中,顯示全部資料

def get_serializer(self,*args,**kwargs): #用*接收 意思為有不同的方法
return self.serializer_class(*args,**kwargs)

#封裝所有的 get 請求方法
class ListModelMixin(object):
def list(self,request):
queryset=self.get_queryset() #取到所有的值
ser_obj=self.get_serializer(queryset,many=True)#用序列化器進行序列化
return Response(ser_obj.data)


# 封裝所有的 post 請求方法
class CreateModelMixin(object):
def create(self,request):#request.data 是去到前端返回的值
ser_obj=self.get_serializer(data=request.data)
if ser_obj.is_valid():
ser_obj.save()
return Response(ser_obj.validated_data)
return Response(ser_obj.errors)

# 封裝所有的 get 請求方法(獲取一條資料)
class RetrieveModelMixin(object):
def retrieve(self,request,id):
book_obj=self.get_queryset().filter(id=id).first()
ser_obj = BookSerializer(book_obj)
return Response(ser_obj.data)

# 封裝所有的 put請求方法(獲取一條資料)
class UpdateModelMixin(object):
def update(self,request,id):
book_obj=self.get_queryset().filter(id=id).first()
ser_obj = self.get_serializer(instance=book_obj, data=request.data, partial=True)
if ser_obj.is_valid():
ser_obj.save()
return Response(ser_obj.validated_data)
return Response(ser_obj.errors)

#封裝刪除 delete 的請求方法
class DestroyModelMixin(object):
def destroy(self,request,id):
book_obj = self.get_queryset().filter(id=id).first()
if not book_obj:
return Response("刪除的物件不存在")
book_obj.delete()
return Response("")

#第二次封裝 ()
class ListCreateAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
pass

class RetrieveUpdateDestroyAPIView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
pass


#此處為第二次封裝的操作
class BookView(ListCreateAPIView):
queryset=Book.objects.all()
serializer_class=BookSerializer

def get(self,request):
return self.list(request)

def post(self,request):
return self.create(request)


class BookEditView(RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer

def get(self,request,id):
return self.retrieve(request,id)

def put(self,request,id):
return self.update(request,id)

def delete(self,request,id):
return self.destory(request,id)



# 第三次封裝 需要之前定義的 請求類
class ModelViewSet(ViewSetMixin,ListCreateAPIView,RetrieveUpdateDestroyAPIView):
pass

#此處為第三次封裝的操作 (自己定義的方法)
class BookModelView(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer

#此處為第三次封裝的操作 (django定義的方法)
class BokModelView(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


#最原始的操作
# class BookView(APIView):
# #檢視所有資料
# def get(self,request):
# book_obj=Book.objects.all()#
# # [book_obj, ]獲取所有資料
# # 用序列化器進行序列化
# ser_obj= BookSerializer(book_obj,many=True)#many=True 顯示 多條資料 單條資料不用
# return Response(ser_obj.data)
#
# #新增資料
# def post(self,request):
# #先確定資料結構及資料型別
# #對前端傳來的資料進行校驗
# book_obj=request.data
# ser_obj=BookSerializer(data=book_obj) #data 使用來進行反序的
# #對虛擬器反序的資料做判斷
# if ser_obj.is_valid():
# ser_obj.save()
# #ser_obj.validated_data 為驗證通過
# return Response(ser_obj.validated_data)
# #驗證不通過 拋異常
# return Response(ser_obj.errors)
#
#
# class BookEditView(APIView):
# #獲取單條id
# def get(self,request,id):
# book_obj=Book.objects.filter(id=id).first()
# ser_obj=BookSerializer(book_obj)
# return Response(ser_obj.data)
#
# #更新單挑資料 用put
# def put(self,request,id):
# book_obj=Book.objects.filter(id=id).first()
# #instance= data= 是反序所用的方法 partial=True 為部分校驗,識別更新的
# ser_obj=BookSerializer(instance=book_obj,data=request.data,
# partial=True
# )
# # 對虛擬器反序的資料做判斷
# if ser_obj.is_valid():
# ser_obj.save()
# return Response(ser_obj.validated_data)
# return Response(ser_obj.error)
#
# #刪除資料
# def delete(self,request,id):
# book_obj=Book.objects.filter(id=id).first()
# if not book_obj:
# return Response('刪除的物件不存在')
# book_obj.delete()
# return Response('')


url路由
from django.conf.urls import url
from djangoDome import views
from SerDemo import views

from rest_framework.routers import DefaultRouter # 幫助我們生成帶引數的路由
router=DefaultRouter() #例項化DsfaultRouter
router.register('^book',views.BokModelView) # 註冊我們的路由以及檢視




urlpatterns = [

url(r'^book/$', views.BookView.as_view()),
url(r'^book/(?P<id>\d+)/$', views.BookEditView.as_view()),

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

django 自己封裝的方法 用pk
url(r'^book/$', views.BokModelView.as_view({"get": "list", "post": "create"})),
url(r'^book/(?P<pk>\d+)/$', views.BokModelView.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),
]


urlpatterns += router.urls