DRF序列化
序列化組件
# 序列化,序列化器會(huì)把模型對象轉(zhuǎn)換成字典,經(jīng)過response以后變成json字符串
# 反序列化,將客戶端發(fā)送過來的數(shù)據(jù),經(jīng)過數(shù)據(jù)校驗(yàn)后變成字典,用序列化器將字典轉(zhuǎn)成模型
序列化
# 注冊rest_framework
# 在models.py中定義表模型
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=6,decimal_places=2)
author = models.CharField(max_length=32)
public = models.CharField(max_length=64)
# 在自定義文件中定義序列化器
from rest_framework import serializers
class BooksSerializer(serializers.Serializer):
name = serializers.CharField()
price = serializers.DecimalField(max_digits=6,decimal_places=2)
author = serializers.CharField()
public = serializers.CharField()
# 在views中定義視圖類
class BookView(APIView):
def get(self,request,id):
book = Book.objects.filter(id=id).first()
book_ser = BooksSerializer(book) # 參數(shù)就是要序列化的對象
# book_ser.data就是序列化后的字典
return Response(book_ser.data) # 也可以用JsonResponse返回,這樣不用注冊rest_framework,但不能通過判斷請求信息區(qū)別渲染
# 配置路由信息
序列化類的字段類型
| 字段 |
字段構(gòu)造方式 |
| BooleanField |
BooleanField() |
| NullBooleanField |
NullBooleanField() |
| CharField |
CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) |
| EmailField |
EmailField(max_length=None, min_length=None, allow_blank=False) |
| RegexField |
RegexField(regex, max_length=None, min_length=None, allow_blank=False) |
| SlugField |
SlugField(max_length=50, min_length=None, allow_blank=False) 正則字段,驗(yàn)證正則模式 [a-zA-Z0-9*-]+ |
| URLField |
URLField(max_length=200, min_length=None, allow_blank=False) |
| UUIDField |
UUIDField(format='hex_verbose') format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" |
| IPAddressField |
IPAddressField(protocol='both', unpack_ipv4=False, **options) |
| IntegerField |
IntegerField(max_value=None, min_value=None) |
| FloatField |
FloatField(max_value=None, min_value=None) |
| DecimalField |
DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位數(shù) decimal_palces: 小數(shù)點(diǎn)位置 |
| DateTimeField |
DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None) |
| DateField |
DateField(format=api_settings.DATE_FORMAT, input_formats=None) |
| TimeField |
TimeField(format=api_settings.TIME_FORMAT, input_formats=None) |
| DurationField |
DurationField() |
| ChoiceField |
ChoiceField(choices) choices與Django的用法相同 |
| MultipleChoiceField |
MultipleChoiceField(choices) |
| FileField |
FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
| ImageField |
ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
| ListField |
ListField(child=, min_length=None, max_length=None) |
| DictField |
DictField(child=) |
序列化類型的選項(xiàng)參數(shù)
| 參數(shù)名稱 |
作用 |
| max_length |
最大長度 |
| min_lenght |
最小長度 |
| allow_blank |
是否允許為空 |
| trim_whitespace |
是否截?cái)嗫瞻鬃址?/td>
|
| max_value |
最小值 |
| min_value |
最大值 |
通用參數(shù):
| 參數(shù)名稱 |
說明 |
| read_only |
表明該字段僅用于序列化輸出,默認(rèn)False |
| write_only |
表明該字段僅用于反序列化輸入,默認(rèn)False |
| required |
表明該字段在反序列化時(shí)必須輸入,默認(rèn)True |
| default |
反序列化時(shí)使用的默認(rèn)值 |
| allow_null |
表明該字段是否允許傳入None,默認(rèn)False |
| validators |
該字段使用的驗(yàn)證器 |
| error_messages |
包含錯(cuò)誤編號與錯(cuò)誤信息的字典 |
| label |
用于HTML展示API頁面時(shí),顯示的字段名稱 |
| help_text |
用于HTML展示API頁面時(shí),顯示的字段幫助提示信息 |
反序列化
# 注意,序列化器中字段的參數(shù)條件應(yīng)該在表模型字段要求的范圍內(nèi)再做限制
def put(self, request, id):
response_msg = {'status': 100, 'msg': '成功'}
book = Book.objects.filter(id=id).first()
book_ser = BooksSerializer(instance=book, validated_data=request.data) # put反序列化 第二個(gè)參數(shù)是修改需要的數(shù)據(jù)
if book_ser.is_valid(): # 數(shù)據(jù)校驗(yàn)
book_ser.save()
response_msg['data'] = book_ser.data
else:
response_msg['status'] = 101
response_msg['msg'] = '數(shù)據(jù)校驗(yàn)失敗'
response_msg['data'] = book_ser.errors
return Response(response_msg)
put反序列化需要實(shí)現(xiàn)序列器類父類的update方法
def update(self, instance, validated_data): # 更新想要反序列化的字段
# instance是book對象,即要修改的對象
# validated_data是校驗(yàn)后的數(shù)據(jù)
instance.name = validated_data.get('name')
instance.price = validated_data.get('price')
instance.author = validated_data.get('author')
instance.public = validated_data.get('public')
instance.save()
return instance
反序列化校驗(yàn)
# 序列化器中定義字段校驗(yàn)
class BooksSerializer(serializers.Serializer):
name = serializers.CharField(max_length=5)
# 序列化器中定義字段校驗(yàn)2
def check_author(data):
if 'sb' in data:
raise ValidationError('含不當(dāng)詞匯')
else:
return data
class BooksSerializer(serializers.Serializer):
author = serializers.CharField(validators=[check_author]) # 此列表傳入函數(shù)內(nèi)存地址
# 序列化器中定義局部鉤子
class BooksSerializer(serializers.Serializer):
def validate_price(self, data):
if float(data) > 10:
return data
else:
raise ValidationError('價(jià)格太低,校驗(yàn)不通過')
# 序列化器中定義全局鉤子
class BooksSerializer(serializers.Serializer):
def validate(self, validated_data):
if float(validated_data.get('price')) > 50 and validated_data.get('public') == '忘記出版社':
raise ValidationError('忘記出版社是廉價(jià)書出版社,你這個(gè)不對')
else:
return validated_data
read_only和write_only
# 在字段參數(shù)中設(shè)置read_only=True則該字段只從數(shù)據(jù)庫讀出,不從外部獲取數(shù)據(jù)修改
# 在字段參數(shù)中設(shè)置write_only=True則該字段只用于獲取外部數(shù)據(jù)修改數(shù)據(jù)庫,而不提供數(shù)據(jù)庫查詢展示
查詢所有
# 將需要過濾參數(shù)的請求放在一個(gè)視圖類,例如查詢部分,修改部分,將不需要過濾參數(shù)的請求放在另外一個(gè)視圖類,例如查詢所有,新增
# 配置URL
# 新建視圖類
class BooksView(APIView):
def get(self,request):
response_msg = {'status': 100, 'msg': '成功'}
books = Book.objects.all()
books_ser = BooksSerializer(books,many=True) # 序列化多條時(shí)需many參數(shù)
response_msg['data'] = books_ser.data
return Response(response_msg)
新增數(shù)據(jù)
class BooksView(APIView):
def post(self, request):
response_msg = {'status': 100, 'msg': '成功'}
book_ser = BooksSerializer(data=request.data)
# 校驗(yàn)字段
if book_ser.is_valid():
book_ser.save()
response_msg['data'] = book_ser.data
else:
response_msg['status'] = 102
response_msg['msg'] = '數(shù)據(jù)校驗(yàn)失敗'
response_msg['data'] = book_ser.errors
return Response(response_msg)
# 需要重寫create方法
class BooksSerializer(serializers.Serializer):
def create(self, validated_data):
book = Book.objects.create(**validated_data)
return book # 這個(gè)對象將序列化后作為data返回給請求端
刪除數(shù)據(jù)
class BookView(APIView):
def delete(self,request,id):
response_msg = {'status': 100, 'msg': '成功'}
book = Book.objects.filter(id=id).delete()
response_msg['data'] = ''
return Response(response_msg)
自定義封裝Response對象
class MyResponse():
def __init__(self):
self.status = '100'
self.msg = '成功'
@property
def get_dict(self):
return self.__dict__
模型類序列化器
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = Book # 指定對應(yīng)哪個(gè)表模型
fields = '__all__'
# fields = ('name','price') 指定字段
# exclude=('name',) # 排除某個(gè)字段,不能同時(shí)與fields = '__all__'一起寫,注意元組
# read_only_fields = ('price',)
# write_only_fields = ('name',) # 棄用
extra_kwargs = {
'price': {'write_only':True,'min_value':0}
}
# 不需要重寫update和create方法
源碼
# 序列化多條需要傳參many=True
def __new__(cls,*args,**kwargs):
if kwargs.pop('many',False):
return cls.many_init(*args,**kwargs) # return list_serializer
return super().__new__(cls,*args,**kwargs)
Serializer高級用法
# 為避免返回?cái)?shù)據(jù)中key值與數(shù)據(jù)庫字段名完全一致而被惡意攻擊,需要在序列化器中將字段名變化,即在序列化器類字段參數(shù)中增加參數(shù):'序列化器字段名'=serializers.CharField(source='數(shù)據(jù)庫字段名')
# source支持models類中的方法
# source支持跨表
# '序列化器字段名'=serializers.CharField(source='跨表表名.字段名')
# 外鍵
# authors = serializers.SerislizerMethodField() #需要一個(gè)配套方法,get_字段名
def get_authors(self,instance): # instance即book
authors=instance.authors.all()
authors_list = []
for author in authors:
authors_list.append('name':author.name,'age':author.age)
return authors_list