1.字段校验、局部钩子、全局钩子
from rest_framework.exceptions import ValidationError
from .models import Publish
class PublishSerializers(serializers.Serializer):
#要序列化的字段
id=serializers.IntegerField(required=False)#前端传入数据,可不填
#allow_blank=True表示需要传入该字段,但是可以为空
#allow_null=True表示可以不需要传入该字段,但是不可以为空
name=serializers.CharField(allow_blank=True,required=False,max_length=10,min_length=2,error_messages={'max_length':
'太长','min_length':'太短'})
addr=serializers.CharField(max_length=20,error_messages={'max_length':'too long'})
phone=serializers.IntegerField(max_value=19999999999,min_value=10000000000,error_messages={'max_value':
'太长','min_value':'太短'})
# 局部钩子:给某个字段做个校验
''' 出版社名字不能包含东京,最大长度不能超过10,最短不能短于2
地址长度不能超过20,没有最短现在,地址不能以上海开头
手机号必须11位
'''
# validate_字段名
def validate_name(self,name):
print(name)
if '东京' in name: raise ValidationError('出版社名字不能包含东京')
else:return name
def validate_addr(self,addr):
print(addr,type(addr))
if addr.startswith('上海'):
raise ValidationError('地址不能以上海开头')
else:return addr
# 全局钩子 出版社名字和地址名字不能一样
def validate(self, attrs):
if attrs.get('name')==attrs.get('addr'):raise ValidationError('出版社名字和地址名字不能一样')
else:return attrs
def create(self, validated_data):#validated_data是校验后的数据
publish=Publish.objects.create(**validated_data)
return publish
def update(self, instance, validated_data):
print('update',instance)#instance=Publish object (pk)#
print('update',instance.pk)#传入的pk值
print(type(instance))#<class 'app01.models.Publish'>
print(validated_data)#{'name': 'a111a', 'addr': '1111', 'phone': 11111111111}
for (key,values) in validated_data.items():
print('key & values',key,values)
setattr(instance,key,values)###重点看,只能用setatttr
# instance[key]=values#b报错 'Publish' object does not support item assignment
# instance.key = values
instance.save()
return instance
2.ModelSerializer
#serializer.py
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from . import models
class BookSerializer(ModelSerializer):
print('BookSerializier')
class Meta:
model = models.Book
fields = ['name', 'price', 'publish_detail', 'author_list', 'publish', 'author']
extra_kwargs = {
'name': {'max_length': 10, 'min_length': 2, 'required': True},
'publish': {'write_only': True},#只用来反序列化
'author': {'write_only': True}
}
publish_detail = serializers.DictField(read_only=True)#只用来序列化
author_list = serializers.ListField(read_only=True)
class PublishSerializer(ModelSerializer):
print('PublishSerializer')
class Meta:
model = models.Publish
fields = '__all__'
class AuthorSerializer(ModelSerializer):
print('AuthorSerializer')
class Meta:
model = models.Author
fields = ['name', 'phone', 'authordetail', 'book_list','age','email']#
extra_kwargs = {
'name': {'max_length': 10, 'min_length': 2, 'required': True},
}
book_list=serializers.ListField(read_only=True)
authordetail = serializers.DictField(read_only=True)
age=serializers.IntegerField(source='author_detail.age')
email=serializers.CharField(source='author_detail.email')
def create(self, validated_data):
print(validated_data)
detail_dict=validated_data.pop('author_detail')###这法子特别注意,方法极好
author_obj_detail=models.AuthorDetail.objects.create(**detail_dict)
validated_data['author_detail_id']=author_obj_detail.pk
print(validated_data)
author_obj=models.Author.objects.create(**validated_data)
print(author_obj)
return author_obj
def update(self, instance, validated_data):
print(instance)
print(validated_data)
return instance
#models.py
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.CharField(max_length=10)
publish = models.ForeignKey(to='Publish', on_delete=models.SET_NULL, null=True)
author = models.ManyToManyField(to='Author')
@property
def publish_detail(self):
return {'id': self.publish.pk, 'name': self.publish.name, 'addr': self.publish.addr}
# @property
def author_list(self):
l = []
for author in self.author.all():
print(author)
l.append({'id': author.pk, 'name': author.name, 'phone': author.phone, 'age': author.author_detail.age})
print(l)
return l
class Publish(models.Model):
name = models.CharField(max_length=32)
addr = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
phone = models.CharField(max_length=11)
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
@property
def authordetail(self):
return {'email': self.author_detail.email, 'age': self.author_detail.age}
# @property
def book_list(self):
l = []
for book in self.book_set.all():
l.append({'id': book.pk, 'price': book.price, 'publish': book.publish.name})
return l
class AuthorDetail(models.Model):
email = models.EmailField()
age = models.SmallIntegerField()