1. 程式人生 > >serializers 序列化器裡面進行 校驗等

serializers 序列化器裡面進行 校驗等

# 宣告序列化器
from rest_framework import serializers
from djangoDome.models import Book

class PublisherSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)

class AuthorSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=32)


#自定義欄位
def my_validate(value):
if 'xxoo' in value.lower():
#拋敏感詞彙
raise serializers.ValidationError('敏感詞彙')
return value


class BookSerializer(serializers.Serializer):
id = serializers.IntegerField(required=False)
title = serializers.CharField(max_length=32,)# 自定義的加這個引數 validators=[my_validate,]
pub_time = serializers.DateField()
category=serializers.CharField(source='get_category_display',read_only=True) #此處為多選時用
#read_only = True 正序查詢
publisher=PublisherSerializer(read_only=True) #多對一
authors=AuthorSerializer(many=True,read_only=True) #多對多用 many=True

#write_only =True 反序查詢 要重新定義
post_category = serializers.IntegerField(write_only=True)
publisher_id = serializers.IntegerField(write_only=True)
author_list = serializers.ListField(write_only=True)

#重寫 create 方法
def create(self, validated_data):
#validated_data 校驗通過的資料 就是book_obj
# 通過ORM操作給Book表增加資料
book_obj=Book.objects.create(title=validated_data['title'],
pub_time=validated_data["pub_time"],
category=validated_data["post_category"],
publisher_id=validated_data["publisher_id"]
)
book_obj.authors.add(*validated_data['author_list'])
return book_obj

# 對單個值進行校驗
def validate_title(self,value):
# value就是title的值 對value處理
if 'xxoo' not in value.lower():
raise serializers.ValidationError('少東西了')
return value

#對所有欄位進行 校驗
def validate(self, attrs):
# attrs 字典有你傳過來的所有的欄位
if 'xxoo' in attrs['title'].lower() and attrs["post_category"] == 1:
return attrs
else:
raise serializers.ValidationError('分類或標題不合符要求')