日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

DRF的序列化组件

發布時間:2023/12/2 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 DRF的序列化组件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

rest

rest下的url

url唯一代表資源,http請求方式來區分用戶行為

url的設計規范

GET: 127.0.0.1:9001/books/      ? # 獲取所有數據

GET: 127.0.0.1:9001/books/{id}      # 獲取單條數據

POST: 127.0.0.1:9001/books/      # 增加數據

DELETE: 127.0.0.1:9001/books/{id}  ? # 刪除數據

PUT: 127.0.0.1:9001/books/{id}      # 修改數據

數據響應規范

GET: 127.0.0.1:9001/books/     ?? # 返回[{}, {}, {}]

GET: 127.0.0.1:9001/books/{id}      # {} 單條數據

POST: 127.0.0.1:9001/books/     ? ?# {} 添加成功的數據

DELETE: 127.0.0.1:9001/books/{id}    # "" 返回空

PUT: 127.0.0.1:9001/books/{id}      # {} 更新后完整的數據

錯誤處理

{ "error": "message" }

解析器組件

  • 解析器組件是用來解析用戶請求的數據的(application/json), content-type

  • 必須繼承APIView

  • request.data觸發解析

APIView的使用

rest_framework是一個app需要在settings里設置

INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework', ]

pip install djangorestframework

from rest_framework.views import APIView
?
class LoginView(APIView):
def get(self, request):
pass

序列化組件

Django自帶的serializer

from django.serializers import serialize # 引入 ? origin_data = Book.objects.all() serialized_data = serialize("json", origin_data)

DRF的序列化組件

接口設計

from rest_framework import serializers #引入

創建一個序列化類

class BookSerializer(serializers.ModelSerializer):class Meta:model = Book# model字段fields = ('title','price','publish','authors','author_list','publish_name','publish_city')# 只需寫入不需要展示的字段extra_kwargs = {'publish': {'write_only': True},'authors': {'write_only': True}}# source為自定義需要展示的信息publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name')publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city')# 多對多字段需要自己手動獲取數據,SerializerMethodField()author_list = serializers.SerializerMethodField() ?def get_author_list(self, book_obj):# 拿到queryset開始循環 [{}, {}, {}, {}]authors = list() ?for author in book_obj.authors.all():authors.append(author.name) ?return authors 創建序列化類

開始序列化

get接口(查詢多條數據) & post接口

class BookView(APIView):def get(self, request):# 獲取querysetorigin_data = Book.objects.all()# 開始序列化serialized_data = BookSerializer(origin_data, many=True)return Response(serialized_data.data)def post(self, request):verified_data = BookSerializer(data=request.data)if verified_data.is_valid():book = verified_data.save()authors = Author.objects.filter(nid__in=request.data['authors'])book.authors.add(*authors)return Response(verified_data.data)else:return Response(verified_data.errors)

get(查詢單條數據) & put接口 & delete接口

class BookFilterView(APIView):def get(self, request, nid):book_obj = Book.objects.get(pk=nid)serialized_data = BookSerializer(book_obj, many=False)return Response(serialized_data.data) ?def put(self, request, nid):book_obj = Book.objects.get(pk=nid)verified_data = BookSerializer(data=request.data, instance=book_obj)if verified_data.is_valid():verified_data.save()return Response(verified_data.data)else:return Response(verified_data.errors) ?def delete(self, request, nid):book_obj = Book.objects.get(pk=nid).delete()return Response()

缺點:

serializers.Serializer無法插入數據,只能自己實現create字段太多,不能自動序列化

接口設計優化

使用視圖組件的mixin進行接口邏輯優化

導入mixin

from rest_framework.mixinx import (ListModelMix,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,RetrieveModelMixin) from rest_framework.generics import GenericAPIView ?

定義序列化類

Class BookSerializer(serializers.ModelSerializer):class Meta:Bookfields = ()...如上

因為使用模塊化編程,建議將定義的序列化類放在單獨的模塊中,再在view.py中導入

from .app_serializers import BookSerializer

定義視圖類?

class BookView(ListModelMix, CreateModelMixin, GenericAPIView):# queryset和serializer_class是固定的寫法queryset = Book.objects.all()serializer_class = BookSerializer def get():return self.list() # 查詢多條def post():return self.create()class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView):queryset = Book.objects.all()serializer_class = BookSerializer ?def get():return self.retrieve() # 查詢單條 ?def delete():return self.destroy() ?def put():return self.update()

注意:

查詢單挑數據的url需要給查詢的id進行正則分組

re_path(r'books/(?P<pk>\d+)/$, views.BookFilterView.as_view())

使用視圖組件的view進行接口邏輯優化

導入模塊

from rest_framework import generics

視圖類?

class BookView(generics.ListCreateAPIView)queryset = Book.objects.all()serializer_class = BookSerializer class BookFilterView(generics.RetrieveUpdateDestroyAPIView):queryset = Book.objects.all()serializer_class = BookSerializer

使用視圖組件的viewset進行接口邏輯優化

導入模塊

from rest_framework.viewsets import ModelViewSet

設計url

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','delete': 'destroy','put': 'update'}))

設計視圖類

class BookView(ModelViewSet):queryset = Book.objects.all()serializer_class = BookSerializer

?

?

?

?

?

?

轉載于:https://www.cnblogs.com/jiaqi-666/p/9416528.html

總結

以上是生活随笔為你收集整理的DRF的序列化组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。