rest_framwork之序列化元件
1 序列化元件
(1)原生序列化
1)匯入
from django.core.serializers import serializer
2)使用
class BookView(APIView):
def get(self, request):
books = Book.objects.all()
#序列化
serialized_data = serialize("json", books)
#返回序列化結果
return HttpResponse(serialized_data)
(2)序列化元件
1)匯入
from rest_framework import serializers
2) 定義序列化類BookSerializer(欄位名必須與model中定義的欄位名一樣,否則會報錯)
class BookSerializer(serializers.Serializer):
title= serializers.CharField(max_length=32)
price=serializers.CharField(max_length=32)
#顯示出來的是Id (多對一,外來鍵欄位)
publish=serializers.CharField(max_length=32)
publish_name = serializers.CharField(max_length=32, source="publish.name", read_only=True)
# 多對多欄位(該欄位名 與下面的get_後面的欄位名必須一樣)
authors_list = serializers.SerializerMethodField()
#多對多欄位的處理(get_是規定寫法,後面的名同上authors_list)
def get_authors_list(self,book_obj):
authors=list()
for author in book_obj.authors.all():
authors.append(author.name)
return authors
3) 定義views.py
#1 首先匯入2)步中自定義的序列化類
class BookView(APIView):
def get(self,request):
#2獲取資料
books=Book.object.all()
#3序列化 (BookSerializer是引入的序列化類)
serialized_data=BookSerializer(books,many=True)
#4返回序列化結果
return Response(serialized_data.data)
(3)通過drf的序列化元件進行GET介面設計
- 定義views.py
class BookFilterView(APIView):
def get(self,request,nid):
book_obj=-Book.objects.get(pk=nid)
ser_data=BookSerializers(book_obj,many=False)
print('ser_data',ser_data)
return Response(ser_data.data)
2 檢視元件(mixins)
檢視元件是用來優化介面邏輯的
(1) 匯入
from rest_framework.mixins import(
ListModelMixin,
CreateModelMixin,
RetrieveModelMixin,
DestoryModelMixin,
UpdateModelMixin
)
from rest_framework.generics import GenericAPIView
(2) 定義序列化類
同上定義的序列化類一樣
(3) 定義view.py
class BookView(ListModelMixin, CreateModelMixin, GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get(self, request):
return self.retrieve(request)
def put(self, request):
return self.update(request)
def delete(self, request):
return self.destroy(request)
3 generic
(1) 匯入
from rest_framework import generic
(2)使用
#檢視新增
class BookView(generic.ListCreateAPIView):
#queryset 與 serializer_class 名字是固定的
queryset = Book.objects.all()
serializer_class=BookSerializer
#更改刪除 檢視單條資料
class BookView(generic.RetricveUpdateDestroyAPIView):
queryset= Book.objects.all()
serializer_class=BookSerializer
4 viewset
(1) 匯入
from rest_framework.viewsets import ModelViewSet
(2) 使用
class BookView(ModelViewSet):
queryset = Book.object.all()
serializer_class=BookSerializer
(3)在url中配置
urlpatterns=[
re_path(r'books/$', views.BookView.as_view({
'get':'list';
'post':'create';
})),
re_path(r'books/(?P<pk>\d+)/$', views.BookView.as_view({
'get':'retrieve',
'put':'update',
'delete':'destory'
}))
]