DRF多表設計與ModelSerializer組件

一:多表設計

(1)模型表字段

"""
Book表:name、price、img、authors、publish、is_delete、create_time

Publish表:name、address、is_delete、create_time
    
Author表:name、age、is_delete、create_time

AuthorDetail表:mobile, author、is_delete、create_time
    
BaseModel基表
    is_delete、create_time
上面四表繼承基表,能夠繼承兩個字段
"""

PS:前端

  (1)表格都有是否刪除字段 建立時間字段mysql

  (2)抽象繼承一個模型表(基表)git

(2)基表的建立

class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    create_time = models.DateTimeField(auto_now_add=True)

    # 設置 abstract = True 來聲明基表,做爲基表的Model不能在數據庫中造成對應的表 重點
    class Meta:
        abstract = True

(3)斷關聯多表關係

(1)做用:sql

  (1)物理上斷開關係提高查找效率數據庫

  (2)防止環裝表關係 致使表關係成爲死表(即不能再操做表 若是想要在從新操做表格 須要刪庫跑路)django

(2)字段設計後端

1:外鍵字段
    (1)一對多:外鍵存放在多的一方
    (2)一對一:從邏輯正反向考慮 如做者與做者詳情 做者刪除 做者詳情級聯更新  做者詳情刪除 做者還在 所以將外鍵存放在詳情表中
    (3)多對多:在關係表中

2:ORM查詢
    (1)正向查詢:經過外鍵字段
    (2)反向查詢:聽過ralated_name

(3)連表操做關係
    (1)做者刪除--->做者詳情刪除---->cascade
    (2)做者刪除--->做者詳情爲空---->set_null
    (3)做者刪除--->做者詳情默認---->set-defalut
    (4)做者刪除--->做者詳情無損---->do_nothing
字段設計
    # 做者詳情表中的
    author = models.OneToOneField(
        to='Author',
        related_name='detail',
        db_constraint=False,
        on_delete=models.CASCADE
    )
    
    # 圖書表中的
    publish = models.ForeignKey(
        to='Publish',
        related_name='books',
        db_constraint=False,
        on_delete=models.DO_NOTHING,
    )
    authors = models.ManyToManyField(
        to='Author'
        related_name='books',
        db_constraint=False,
    )

PS:api

  (1)多對多表關係不能設置on_deleteapp

  (2)一對一,一對多必須設置on_delete ide

  (3)1.X的Django默認設置on_delete 2.X須要手工設置

(4)模型表建立

# 1) 基表
class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    create_time = models.DateTimeField(auto_now_add=True)

    # 做爲基表的Model不能在數據庫中造成對應的表,設置 abstract = True
    class Meta:
        abstract = True


class Book(BaseModel):
    """name、price、img、authors、publish、is_delete、create_time"""
    name = models.CharField(max_length=64)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    img = models.ImageField(upload_to='img', default='img/default.jpg')
    publish = models.ForeignKey(
        to='Publish',
        db_constraint=False,  # 斷關聯
        related_name='books',  # 反向查詢字段:publish_obj.books 就能訪問全部出版的書
        on_delete=models.DO_NOTHING,  # 設置連表操做關係
    )
    authors = models.ManyToManyField(
        to='Author',
        db_constraint=False,
        related_name='books'
    )

    # 序列化插拔式屬性 - 完成自定義字段名完成連表查詢
    @property
    def publish_name(self):
        return self.publish.name

    @property
    def author_list(self):
        return self.authors.values('name', 'age', 'detail__mobile').all()

    class Meta:
        db_table = 'book'
        verbose_name = '書籍'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

class Publish(BaseModel):
    """name、address、is_delete、create_time"""
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=64)

    class Meta:
        db_table = 'publish'
        verbose_name = '出版社'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

class Author(BaseModel):
    """name、age、is_delete、create_time"""
    name = models.CharField(max_length=64)
    age = models.IntegerField()

    class Meta:
        db_table = 'author'
        verbose_name = '做者'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

class AuthorDetail(BaseModel):
    """mobile, author、is_delete、create_time"""
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
        to='Author',
        db_constraint=False,
        related_name='detail',
        on_delete=models.CASCADE,
    )

    class Meta:
        db_table = 'author_detail'
        verbose_name = '做者詳情'
        verbose_name_plural = verbose_name
    def __str__(self):
        return '%s的詳情' % self.author.name
模型表

二:ModelSerializer

(1)settings文件配置

INSTALLED_APPS = [
    # 註冊rest_framework
    'rest_framework',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database',
        'USER': 'root',
        'PASSWORD': '123',
    }
}
"""
任何__init__文件
import pymysql
pymysql.install_as_MySQLdb()
"""

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
settings文件配置

(2)主路由層配置

from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('api.urls')),
    url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
]
主路由

(3)子路由層

from django.conf.urls import url
from . import views
urlpatterns = [
    url('^books/$', views.Book.as_view()),
    url('^books/(?P<primary_key>.*)/$', views.Book.as_view()),
    url(r'^v2/books/$', views.V2Book.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.V2Book.as_view()),
]

(3)序列化層:

(1)項目下建立一下py文件

serializers.py

(2)導入相應的模塊

from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError   # 導入報錯信息
from . import models    # 導入模型表

(3)基礎使用方式

class BookModelSerializer(ModelSerializer):  # 建立序列化類class Meta:     
        model = models.Book # 序列化類關聯的model類  後面根據類目至關於拿到類的名稱空間 
        fields = ('name', 'price', 'img', 'author_info', )      # 參與序列化的字段

(4)自定義連表深度

# 能夠單獨做爲Publish接口的序列化類,也能夠做爲Book序列化外鍵publish輔助的序列化組件
class PublishModelSerializer(ModelSerializer):
    class Meta:
        model = models.Publish
        fields = ('name', 'address')

class BookModelSerializer(ModelSerializer):

    # 自定義連表深度 - 子序列化方式 - 該方式不能參與反序列化,使用在序列化反序列化共存時,不能書寫
    publish = PublishModelSerializer()
    class Meta:
        # 序列化類關聯的model類
        model = models.Book
        # 參與序列化的字段
        fields = ('name', 'price', 'img', 'author_info','publish' )

(5)小特性瞭解知識點

class BookModelSerializer(ModelSerializer):
    # 瞭解: 該方式設置的序列化字段,必須在fields中聲明
     publish_address = SerializerMethodField()
     def get_publish_address(self, obj):
         return obj.publish.address
      
         fields = '__all__'    # 全部字段
 
         exclude = ('id', 'is_delete', 'create_time')     # 與fields不共存,exclude排除哪些字段
    
         depth = 1      # 自動連表深度

(6)視圖層查詢數據

class Book(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                book_obj = models.Book.objects.get(pk=pk, is_delete=False)
                book_data = serializers.BookModelSerializer(book_obj).data
            except:
                return Response({
                    'status': 1,
                    'msg': '書籍不存在'
                })
        else:
            book_query = models.Book.objects.filter(is_delete=False).all()
            book_data = serializers.BookModelSerializer(book_query, many=True).data
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_data
        })

(7)序列化層

class PublishModelSerializer(ModelSerializer):
    class Meta:
        model = models.Publish
        fields = ('name', 'address')

class BookModelSerializer(ModelSerializer):
 
    # 自定義連表深度 - 子序列化方式 - 該方式不能參與反序列化,使用在序列化反序列化共存時,不能書寫
    publish = PublishModelSerializer()

    class Meta:
        # 序列化類關聯的model類
        model = models.Book
        # 參與序列化的字段
        fields = ('name', 'price', 'img', 'author_info', 'publish')

 (8)視圖層數據提交

class Book(APIView):
    def post(self, request, *args, **kwargs):
        request_data = request.data
        book_ser = serializers.BookModelDeserializer(data=request_data)
        # raise_exception=True:當校驗失敗,立刻終止當前視圖方法,拋異常返回給前臺
        book_ser.is_valid(raise_exception=True)
        book_obj = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.BookModelSerializer(book_obj).data
        })

(9)反序列化層

class BookModelDeserializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price', 'publish', 'authors')
        # extra_kwargs 用來完成反序列化字段的 系統校驗規則
        extra_kwargs = {
            'name': {
                'required': True,
                'min_length': 1,
                'error_messages': {
                    'required': '必填項',
                    'min_length': '過短',
                }
            }
        }
    
    # 局部鉤子
    def validate_name(self, value):
        # 書名不能包含 g 字符
        if 'g' in value.lower():
            raise ValidationError('該g書不能出版')
        return value
    # 全局鉤子
    def validate(self, attrs):
        publish = attrs.get('publish')
        name = attrs.get('name')
        if models.Book.objects.filter(name=name, publish=publish):
            raise ValidationError({'book': '該書已存在'})
        return attrs

    # ModelSerializer類已經幫咱們實現了 create 與 update 方法

三:序列化反序列化二合一

(1)fields中設置全部須要參與序列化與反序列化的字段

(2)extra_kwargs 設置哪些字段是隻參與序列化與參與反序列化

  (1)read_only ---> 只參與序列化

  (2)write_only ---> 只參與反序列化

(3)設置全局鉤子 局部鉤子 以及須要校驗的字段

(4)代碼展現

class V2BookModelDeSerializer(ModelSerializer):
    class Meta:
        model = models.Book  # 參與序列化的模型表
        fields = ('name', 'price', 'img', 'authors_info', 'publish_name', 'publish', 'authors')   # 參與序列化與反序列化的字段

        extra_kwargs = {    # 設置額外的約束條件
            'name': {  
                'required': True,
                'min_length': 1,
                'error_messages': {
                    'required': '必填項',
                    'min_length': '過短',
                }
            },
            'publish': {
                'write_only': True
            },
            'authors': {
                'write_only': True
            },
            'img': {
                'read_only': True,
            },
            'author_list': {
                'read_only': True,
            },
            'publish_name': {
                'read_only': True,
            }
        }

    def validate_name(self, value):   # 局部鉤子
        # 書名不能包含 g 字符
        if 'g' in value.lower():
            raise ValidationError('該g書不能出版')
        return value
 
    def validate(self, attrs):   # 全局鉤子
        publish = attrs.get('publish')
        name = attrs.get('name')
        if models.Book.objects.filter(name=name, publish=publish):
            raise ValidationError({'book': '該書已存在'})
        return attrs

(5)視圖層代碼變更

class V2Book(APIView):
    # 查詢
    def get(self, request, *args, **kwargs):
        primary_key = kwargs.get('primary_key')

        if not primary_key:
            book_obj_list = models.Book.objects.filter(is_delete=False).all()  # 查詢全部沒被刪除的對象
            book_data = serializers.V2BookModelDeSerializer(book_obj_list, many=True).data
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': book_data
            })

        try:
            book_obj = models.Book.objects.get(pk=primary_key, is_delete=False)
            book_data = serializers.V2BookModelDeSerializer(book_obj).data
        except:
            return Response({
                'msg': '查詢錯誤 該書籍不存在',
                'status': 1
            })

        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_data
        })

    # 添加
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict) and request_data is not None:
            many = False   # 添加單條數據
        elif isinstance(request_data, list) and request_data is not None:
            many = True   # 添加多條數據
        else:
            return Response({
                'status': 1,
                'msg': '數據錯誤'
            })

        book_ser = serializers.V2BookModelDeSerializer(data=request_data, many=many)
        if book_ser.is_valid(raise_exception=True):   # 當前校驗設備 立馬終止程序運行 拋出異常
            book_results = book_ser.save()
            book_data = serializers.V2BookModelDeSerializer(book_results, many=many).data   # many = many必定加上 由於序列化的假設多個數據 還須要將參與序列化的數據給返回出去    
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': book_data
            })

    def delete(self, request, *args, **kwargs):
        primary_key = kwargs.get('primary_key')
        data = request.data

        if primary_key:
            pks = [primary_key]   # 刪除多條數據

        else:
            pks = data.get('pks')  # 獲取前臺傳入的多個數據
            print(pks)
        book_obj = models.Book.objects.filter(pk__in=pks, is_delete=False)   # 判斷後端的pk在不在上述列表中 且篩選沒有被刪除的字段

        if book_obj:
            book_obj.update(is_delete=True)
            return Response({
                'status': 1,
                'msg': '刪除失敗'
            })

        return Response({
            'status': 0,
            'msg': '刪除成功',
        })

 (6)單條數據總體更改

    def put(self, request, *args, **kwargs):
        pk = kwargs.get('primary_key')  # 獲取更改的對象的主鍵 經過主鍵進行篩選
 
        request_data = request.data  # 獲取更改數據的值
        try:
            book_obj = models.Book.objects.filter(pk=pk).first()   # 進行異常捕獲 防止前端輸入的pk不是整形
        except:

            return Response(
                {
                    'status': 1,
                    'msg': '數據不存在',

                })
        '''
        instance:要更改的模型表實例化產生的對象
        data:要更改的數據
        '''

        book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data) 

        book_ser.is_valid(raise_exception=True)

        book_ser_obj = book_ser.save()
        data = serializers.BookModelSerializer(book_ser_obj).data
        return Response(
            {
                'status': 0,
                'msg': 'ok',
                'results': data
            }
        )

(7)單條局部修改

    def patch(self, request, *args, **kwargs):

        pk = kwargs.get('primary_key')

        request_data = request.data   # 要更改的數據
        try:

            book_obj = models.Book.objects.filter(pk=pk).first()  # 要更改模型表實例化的對象
        except:
            return Response(
                {
                    'status': 1,
                    'msg': '數據不存在',

                })

        '''
          instance:要更改模型表實例化的對象
          data:要更改的數據
          partial:設置部分字段能夠選填
          '''
        book_ser = serializers.BookModelSerializer(instance=book_obj,data=request_data,partial=True)
        book_ser.is_valid(raise_exception=True)
        book_ser_obj = book_ser.save()
        data = serializers.BookModelSerializer(book_ser_obj).data
        return Response(
            {
                'status': 0,
                'msg': 'ok',
                'results': data
            }
        )

 (8)單改與局部總體修改

# 序列化層
class BookListSerializer(ListSerializer):
    def update(self, instance, validated_data):
        print(instance)  # 要更新的對象們
        print(validated_data)  # 更新的對象對應的數據們
        print(self.child)  # 服務的模型序列化類 - BookModelSerializer
        for index, obj in enumerate(instance):
            self.child.update(obj, validated_data[index])   # 獲取須要更新的對象 以及更新的數據
        return instance

class BookModelSerializer(ModelSerializer):


    class Meta:
        # 羣改,須要設置 自定義ListSerializer,重寫羣改的 update 方法
        list_serializer_class = BookListSerializer

PS:

  (1)因爲源碼問題 咱們須要本身定義ListSerializer的update方法

(9)視圖層

    def patch(self, request, *args, **kwargs):
        pk = kwargs.get('primary_key')

        request_data = request.data  # [{'pk': 1, 'name': 123}, {'pk': 3, 'price': 7}, {'pk': 7, 'publish': 2}] 前臺傳入的數據

        if pk and isinstance(request_data, dict):
            pks = [pk, ]
            request_data = [request_data, ]
        elif not pk and isinstance(request_data, list):
            pks = []   # 定義個一個空列表存放主鍵值
            for dic in request_data:
                pk = dic.pop('pk', None)   # for循環上述數據 將主鍵傳入上述列表 若是設置none防止主鍵不存在
                if not pk:
                    return Response(
                        {
                            'status': 2,
                            'msg': '數據錯誤'
                        }
                    )
                pks.append(pk)   # 將主鍵加入上述列表
        else:
            return Response(
                {
                    'status': 1,
                    'msg': "數據查詢錯誤"
                }
            )

        objs = []   # 存放序列化的對象
        new_request_data = []   # 存放須要反序列化的數據

        for index, pk in enumerate(pks):
            try:    # 防止主鍵不存在
                obj = models.Book.objects.get(pk=pk,is_delete=False)
                objs.append(obj)
                new_request_data.append(request_data[index])   # 上述pks都是合法的主鍵 經過獲取主鍵的索引 而後去原數據取值
            except:  # 主鍵不存在 直接跳出本次循環 進入下一次循環
                #  重點:反面教程 - pk對應的數據有誤,將對應索引的data中request_data中移除
                # index = pks.index(pk)
                # request_data.pop(index)
                continue

        book_ser = serializers.BookModelSerializer(instance=objs, data=new_request_data, many=True, partial=True)
        book_ser.is_valid(raise_exception=True)
        book_obj = book_ser.save()
        data = serializers.BookModelSerializer(book_obj, many=True).data

        return Response({
            'status': 0,
            'msg': "ok",
            "results": data
        })

 四:視圖類與序列化類傳參

(1)做用:

  (1)某些序列化類可能會須要視圖層的數據

  (2)context可讓序列化類獲取視圖類內部的參數

(2)使用方式

  (1)視圖類在序列化的時候傳入context的方法

  (2)序列化類經過self.context拿到傳入的數據

(3)視圖類

class Book(APIView):
    def post(self, request, *args, **kwargs):
        book_ser = serializers.BookModelSerializer(data=request_data,context={'request':request})
        book_ser.is_valid(raise_exception=True)
        book_result = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.BookModelSerializer(book_result).data
        })

(4)序列化類

class BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price')
    def validate_name(self, value):
        print(self.context.get('request').method)   # 拿到後端使用的方法
        return value

五:Reponse封裝

from rest_framework.response import Response


class APIResponse(Response):
    '''
    data_status:數據狀態碼
    data_msg:數據返回消息
    headers:請求頭
    results:響應結果
    exception:報錯信息
    http_status:http狀態碼
    kwargs:後端是否傳入額外數據 例如token等


    '''

    def __init__(self, data_status=0, data_msg='ok', headers=None, results=None, exception=False, http_status=None,
                 **kwargs):
        data = {
            'status': data_status,
            'msg': data_msg
        }

        '''
        Response({
        'status': 0,
        'msg': 'ok',
        'results': [],
        'token': ''  # 有這樣的額外的key-value數據結果
        },status=http_status,headers=headers,exception=True|False)

         APIResponse() => Response({'status': 0,'msg': 'ok'})
#
#

        '''

        # 判斷是否有返回結果 若是有則返回
        if results is not None:
            data['results'] = results

        # 判斷後端時候給序列化傳額外數據
        if kwargs is not None:
            data.update(kwargs)

        super().__init__(data=data, status=http_status, exception=exception, headers=headers)



"""
Response({
    'status': 0,
    'msg': 'ok',
    'results': [],
    'token': ''  # 有這樣的額外的key-value數據結果
},status=http_status,headers=headers,exception=True|False)

APIResponse() => Response({'status': 0,'msg': 'ok'})
"""
相關文章
相關標籤/搜索