序列化組件

1、Serializer

1.序列化準備:

模型層:models.py

class User(models.Model):
    SEX_CHOICES = [
        [0, ''],
        [1, ''],
    ]
    name = models.CharField(max_length=64)
    pwd = models.CharField(max_length=32)
    phone = models.CharField(max_length=11, null=True, default=None)
    sex = models.IntegerField(choices=SEX_CHOICES, default=0)
    icon = models.ImageField(upload_to='icon', default='icon/default.jpg')

    class Meta:
        db_table = 'old_boy_user'
        verbose_name = '用戶'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s' % self.name

後臺管理層:admin.py

from django.contrib import admin
from . import models

admin.site.register(models.User)

配置層:settings.py

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

# 配置數據庫
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day70',
        'USER': 'root',
        'PASSWORD': '123'
    }
}

# media資源
MEDIA_URL = '/media/'  # 後期高級序列化類與視圖類,會使用該配置
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # media資源路徑

# 國際化配置
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

主路由:項目下urls.py

urlpatterns = [
    # ...
    url(r'^api/', include('api.urls')),

    url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
]

子路由:應用下urls.py

urlpatterns = [
    url(r'^users/$', views.User.as_view()),
    url(r'^users/(?P<pk>.*)/$', views.User.as_view()),
]

2.序列化使用

序列化層:api/serializers.py

"""
1)設置須要返回給前臺 那些model類有對應的 字段,不須要返回的就不用設置了
2)設置方法字段,字段名能夠隨意,字段值有 get_字段名 提供,來完成一些須要處理在返回的數據
"""
# 序列化組件 - 爲每個model類經過一套序列化工具類
# 序列化組件的工做方式與django froms組件很是類似
from rest_framework import serializers, exceptions
from django.conf import settings

from . import models

class UserSerializer(serializers.Serializer):
    name = serializers.CharField()
    phone = serializers.CharField()
    # 序列化提供給前臺的字段個數由後臺決定,能夠少提供,
    # 可是提供的數據庫對應的字段,名字必定要與數據庫字段相同
    # sex = serializers.IntegerField()
    # icon = serializers.ImageField()

    # 自定義序列化屬性
    # 屬性名隨意,值由固定的命名規範方法提供:
    #       get_屬性名(self, 參與序列化的model對象)
    #       返回值就是自定義序列化屬性的值
    gender = serializers.SerializerMethodField()
    def get_gender(self, obj):
        # choice類型的解釋型值 get_字段_display() 來訪問
        return obj.get_sex_display()


    icon = serializers.SerializerMethodField()
    def get_icon(self, obj):
        # settings.MEDIA_URL: 本身配置的 /media/,給後面高級序列化與視圖類準備的
        # obj.icon不能直接做爲數據返回,由於內容雖然是字符串,可是類型是ImageFieldFile類型
        return '%s%s%s' % (r'http://127.0.0.1:8000', settings.MEDIA_URL, str(obj.icon))

視圖層

"""
1)從數據庫中將要序列化給前臺的model對象,或是對個model對象查詢出來
    user_obj = models.User.objects.get(pk=pk) 或者
    user_obj_list = models.User.objects.all()
2)將對象交給序列化處理,產生序列化對象,若是序列化的是多個數據,要設置many=True
    user_ser = serializers.UserSerializer(user_obj) 或者
    user_ser = serializers.UserSerializer(user_obj_list, many=True)
3)序列化 對象.data 就是能夠返回給前臺的序列化數據
    return Response({
        'status': 0,
        'msg': 0,
        'results': user_ser.data
    })
"""
class User(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                # 用戶對象不能直接做爲數據返回給前臺
                user_obj = models.User.objects.get(pk=pk)
                # 序列化一下用戶對象
                user_ser = serializers.UserSerializer(user_obj)
                # print(user_ser, type(user_ser))
                return Response({
                    'status': 0,
                    'msg': 0,
                    'results': user_ser.data
                })
            except:
                return Response({
                    'status': 2,
                    'msg': '用戶不存在',
                })
        else:
            # 用戶對象列表(queryset)不能直接做爲數據返回給前臺
            user_obj_list = models.User.objects.all()
            # 序列化一下用戶對象
            user_ser_data = serializers.UserSerializer(user_obj_list, many=True).data
            return Response({
                'status': 0,
                'msg': 0,
                'results': user_ser_data
            })

 

2、ModelSerializer

配置:settings.py

INSTALLED_APPS = [
    # ...
    'rest_framework',
]
​
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dg_proj',
        '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')
View Code

路由

#
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}),
]
​
​
#
from django.conf.urls import url
from . import views
urlpatterns = [
    
]
View Code

多表設計

""" 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 上面四表繼承基表,能夠繼承兩個字段 """

基表

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

斷關聯多表關係

""" 一、外鍵位置: 一對多 - 外鍵放多的一方
       一對一 - 從邏輯正反向考慮,如做者表與做者詳情表,做者刪除級聯刪除詳情,詳情刪除做者依舊存在,因此建議外鍵在詳情表中 
      多對多 - 外鍵在關係表中
   二、ORM正向方向連表查找:
      正向:經過外鍵字段 eg: author_detial_obj.author
      反向:經過related_name的值 eg:author_obj.detail 
                                     注:依賴代碼見下方 
   三、連表操做關係:
     1)做者刪除,詳情級聯 - on_delete=models.CASCADE
     2)做者刪除,詳情置空 - null=True, on_delete=models.SET_NULL 
     3)做者刪除,詳情重置 - default=0, on_delete=models.SET_DEFAULT 
     4)做者刪除,詳情不動 - on_delete=models.DO_NOTHING
                               注:拿做者與做者詳情表舉例 
   四、外鍵關聯字段的參數 - 如何實現 斷關聯、目前表間操做關係、方向查詢字段 
     i)做者詳情表中的 author = models.OneToOneField( to='Author', related_name='detail', db_constraint=False, on_delete=models.CASCADE )
    ii)圖書表中的
 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,
)
注:ManyToManyField不能設置on_delete,OneToOneField、ForeignKey必須設置on_delete(django1.x系統默認級聯,可是django2.x必須手動明確)
"""

model類

from django.db import models

圖書管理系統:Book、Author、AuthorDetail、Publish

""" 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 """

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
 
View Code

序列化

序列化層:api/serializers.py

from rest_framework.serializers import ModelSerializer, SerializerMethodField from rest_framework.exceptions import ValidationError from . import models

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

class BookModelSerializer(ModelSerializer): # 瞭解: 該方式設置的序列化字段,必須在fields中聲明 # publish_address = SerializerMethodField() # def get_publish_address(self, obj): # return obj.publish.address

# 自定義連表深度 - 子序列化方式 - 該方式不能參與反序列化,使用在序列化反序列化共存時,不能書寫
publish = PublishModelSerializer()
​
class Meta:
    # 序列化類關聯的model類
    model = models.Book
    # 參與序列化的字段
    fields = ('name', 'price', 'img', 'author_list', 'publish')
​
    # 瞭解知識點
    # 全部字段
    # fields = '__all__'
    # 與fields不共存,exclude排除哪些字段
    # exclude = ('id', 'is_delete', 'create_time')
    # 自動連表深度
    # depth = 1

視圖層:api/views.py

# 序列化
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
        })

路由層:api/urls.py

urlpatterns = [ url(r'^books/$', views.Book.as_view()), url(r'^books/(?P<pk>.*)/$', views.Book.as_view()), ]

反序列化

序列化層:api/serializers.py

# 反序列化
class BookModelDeserializer(ModelSerializer):
    class Meta:
        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):
            if 'g' in value.lower():
                raise ValidationError('該書不能出版')
            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

視圖層:api/views.py

    # 反序列化
    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
        })

路由層:api/urls.py

urlpatterns = [ url(r'^books/$', views.Book.as_view()), url(r'^books/(?P<pk>.*)/$', views.Book.as_view()), ]

序列化與反序列化整合(重點)

"""
1) fields中設置全部序列化與反序列化字段
2) extra_kwargs劃分只序列化或只反序列化字段
    write_only:只反序列化
    read_only:只序列化
    自定義字段默認只序列化(read_only)
3) 設置反序列化所需的 系統、局部鉤子、全局鉤子 等校驗規則
"""

序列化層:api/serializers.py

class V2BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price', 'img', 'author_list', '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

視圖層:api/views.py

    # 單增:傳的數據是與model對應的字典
    # 羣增:傳的數據是 裝多個 model對應字典 的列表
    def post(self,request,*args,**kwargs):
        request_data = request.data
        if isinstance(request_data,dict):
            many = False
        elif isinstance(request_data,list):
            many = True
        else:
            return Response({
                'status':1,
                'msg':'數據有誤',
            })
        book_ser = serializers.V2BookModelSerializer(data=request_data,many=many)

        book_ser.is_valid(raise_exception=True)
        book_result = book_ser.save()
        return Response({
            'status':0,
            'msg':'ok',
            'results':serializers.V2BookModelSerializer(book_result,many=many).data
        })

    # 單刪:有pk
    # 羣刪:有pks   |  {"pks": [1, 2, 3]}

    def delete(self,request,*args,**kwargs):
        pk = kwargs.get('pk')
        if pk:
            pks = [pk]
        else:
            pks = request.data.get('pks')
        if models.Book.objects.filter(pk__in=pks,is_delete=False).update(is_delete=True):
            return Response({
            'status':0,
            'msg':'刪除成功'
        })
        return Response({
            'status':1,
            'msg':'刪除失敗'
        })

路由層:api/urls.py

urlpatterns = [ url(r'^v2/books/$', views.V2Book.as_view()), url(r'^v2/books/(?P<pk>.*)/$', views.V2Book.as_view()), ]

3、ListModelSerializer

總體單改

路由層、模型層、序列化層不須要作修改,只須要處理視圖層:views.py

"""
1) 單總體改,說明前臺要提供修改的數據,那麼數據就須要校驗,校驗的數據應該在實例化「序列化類對象」時,賦值給data
2)修改,就必須明確被修改的模型類對象,並在實例化「序列化類對象」時,賦值給instance
3)總體修改,全部校驗規則有required=True的字段,都必須提供,由於在實例化「序列化類對象」時,參數partial默認爲False


注:若是partial值設置爲True,就是能夠局部改
1)單總體修改,通常用put請求:
V2BookModelSerializer(
    instance=要被更新的對象, 
    data=用來更新的數據,
    partial=默認False,必須的字段所有參與校驗
)
2)單局部修改,通常用patch請求:
V2BookModelSerializer(
    instance=要被更新的對象, 
    data=用來更新的數據,
    partial=設置True,必須的字段都變爲選填字段
)
    注:partial設置True的本質就是使字段 required=True 校驗規則失效
"""
class V2Book(APIView):
    # 單總體改: 對 v2/books/(pk)/ 傳的數據是與model對應的字典{name|price|publish|authors}
    def put(self, request, *args, **kwargs):
        request_data = request.data
        pk = kwargs.get('pk')
        old_book_obj = models.Book.objects.filter(pk=pk).first()
        # 目的:將衆多數據的校驗交給序列化類來處理 - 讓序列化類扮演反序列化角色,校驗成功後,序列化類來幫你入庫
        book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data, partial=False)
        book_ser.is_valid(raise_exception=True)
        # 校驗經過,完成數據的更新:要更新的目標,用來更新的新數據
        book_obj = book_ser.save()

        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2BookModelSerializer(book_obj).data
        })

單與總體局部修改

序列化層:serializers.py

# 重點:ListSerializer與ModelSerializer創建關聯的是:
# ModelSerializer的Meta類的 - list_serializer_class
class V2BookListSerializer(ListSerializer):
    def update(self, instance, validated_data):
        # print(instance)  # 要更新的對象們
        # print(validated_data)  # 更新的對象對應的數據們
        # print(self.child)  # 服務的模型序列化類 - V2BookModelSerializer
        for index, obj in enumerate(instance):
            self.child.update(obj, validated_data[index])
        return instance
    
# 原模型序列化類變化
class V2BookModelSerializer(ModelSerializer):
    class Meta:
        # ...
        # 羣改,須要設置 自定義ListSerializer,重寫羣改的 update 方法
        list_serializer_class = V2BookListSerializer
    # ...

視圖層:views.py

class V2Book(APIView):
    # 單局部改:對 v2/books/(pk)/ 傳的數據,數據字段key都是選填
    # 羣局部改:對 v2/books/ 
    # 請求數據 - [{pk:1, name:123}, {pk:3, price:7}, {pk:7, publish:2}]
    def patch(self, request, *args, **kwargs):
        request_data = request.data
        pk = kwargs.get('pk')

        # 將單改,羣改的數據都格式化成 pks=[要須要的對象主鍵標識] | request_data=[每一個要修改的對象對應的修改數據]
        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:1, name:123}, {pk:3, price:7}, {pk:7, publish:2}],拿一個個字典
                pk = dic.pop('pk', None)
                if pk:
                    pks.append(pk)
                else:
                    return Response({
                        'status': 1,
                        'msg': '數據有誤',
                    })
        else:
            return Response({
                'status': 1,
                'msg': '數據有誤',
            })

        # pks與request_data數據篩選,
        # 1)將pks中的沒有對應數據的pk與數據已刪除的pk移除,request_data對應索引位上的數據也移除
        # 2)將合理的pks轉換爲 objs
        objs = []
        new_request_data = []
        for index, pk in enumerate(pks):
            try:
                # pk對應的數據合理,將合理的對象存儲
                obj = models.Book.objects.get(pk=pk)
                objs.append(obj)
                # 對應索引的數據就須要保存下來
                new_request_data.append(request_data[index])
            except:
                # 重點:反面教程 - pk對應的數據有誤,將對應索引的data中request_data中移除
                # index = pks.index(pk)
                # request_data.pop(index)
                continue

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

        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2BookModelSerializer(book_objs, many=True).data
        })

 

4、視圖類傳遞參數給序列化類

 1)在視圖類中實例化序列化對象時,能夠設置context內容
 2)在序列化類中的局部鉤子、全局鉤子、create、update方法中,均可以用self.context訪問視圖類傳遞過來的內容


 需求:
 1) 在視圖類中,能夠經過request獲得登錄用戶request.user
 2) 在序列化類中,要完成數據庫數據的校驗與入庫操做,可能會須要知道當前的登錄用戶,但序列化類沒法訪問request
 3) 在視圖類中實例化序列化對象時,將request對象傳遞進去

視圖層:views.py

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
        })

序列化層:serializers.py

class BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price')
    def validate_name(self, value):
        print(self.context.get('request').method)
        return value
相關文章
相關標籤/搜索