一.序列化組件的使用及接口設計git
1.經過序列化組件進行get和post接口設計數據庫
建立models.pydjango
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5,decimal_places=2) publish = models.ForeignKey(to="Publish",related_name="book",related_query_name="book_query",on_delete=models.CASCADE) authors = models.ManyToManyField(to="Author")
urls.pyapp
from django.contrib import admin from django.urls import path,re_path,include from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('books/', views.BookView.as_view()), ]
app_serializers.pypost
from rest_framework import serializers # 第二步, 建立一個序列化類,字段類型不必定要跟models的字段一致 class BookSerializer(serializers.Serializer): # nid = serializers.CharField(max_length=32) title = serializers.CharField(max_length=128) price = serializers.DecimalField(max_digits=5, decimal_places=2) publish = serializers.CharField() # 外鍵字段, 顯示__str__方法的返回值 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') # authors = serializers.CharField(max_length=32) # book_obj.authors.all() # 多對多字段須要本身手動獲取數據,SerializerMethodField() authors_list = serializers.SerializerMethodField() def get_authors_list(self, book_obj): author_list = list() for author in book_obj.authors.all(): author_list.append(author.name) return author_list def create(self, validated_data): # {'title': 'Python666', 'price': Decimal('66.00'), 'publish': '2'} validated_data['publish_id'] = validated_data.pop('publish') book = Book.objects.create(**validated_data) return book
view.pyurl
from rest_framework.views import APIView
from rest_framework.response import Responsespa
from .models import (
Book,
Publish,
Author,
)
from .app_serializers import BookSerializer設計
class BookView(APIView): def get(self, request): # 第三步,獲取queryset origin_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)
總結:
1. serializers.Serializer沒法插入數據,只能本身實現create
2. 字段太多,不能自動序列化rest
2.經過序列化組件進行get單條數據和put,delete接口設計code
get單條數據接口設計
1. 定義url
2. 獲取數據對象
3. 開始序列化:serialized_data = BookSerializer(book_obj, many=False)
4. 返回數據:serialized_data.data
put數據接口設計
1. 定義url
2. 獲取數據對象
2.1 book_obj = Book.objects.get(pk=1)
3. 開始序列化(驗證數據,save())
3.1 verified_data = BookSerializer(instance=book_obj, many=False)
4. 驗證成功寫入數據庫,驗證失敗返回錯誤
4.1 verified_data.is_valid()
deltet數據接口設計
1.定義url
2.獲取數據對象並刪除
Book.objects.get(pk=nid).delete()
url.py
from django.urls import re_path from serializer import views urlpatterns = [ re_path(r'books/$', views.BookView.as_view()), re_path(r'books/(?P<pk>\d+)/$', views.BookFilterView.as_view()), ]
app_serializers.py
from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'price', 'publish', 'authors', 'author_list', 'publish_name', 'publish_city' ) extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'write_only': True} } 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') 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
view.py
from rest_framework.views import APIView from rest_framework.response import Response from .app_serializers import BookSerializer from .models import ( Book, Publish, Author, ) 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()