标签:active lin set 执行 save operator 特性 response 调用
模型类
class BookInfo(models.Model):
btitle = models.CharField(max_length=20, verbose_name=‘名称‘)
bpub_date = models.DateField(verbose_name=‘发布日期‘, null=True)
bread = models.IntegerField(default=0, verbose_name=‘阅读量‘)
bcomment = models.IntegerField(default=0, verbose_name=‘评论量‘)
image = models.ImageField(upload_to=‘booktest‘, verbose_name=‘图片‘, null=True)
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label=‘ID‘, read_only=True) # read_only只在序列化中使用, 反序列化不使用
# write_only=True 只在反序列化中处理该字段
# 剩下的字段序列化和反序列化都可以使用
btitle = serializers.CharField(label=‘名称‘, max_length=20)
bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
bread = serializers.IntegerField(label=‘阅读量‘, required=False)
bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
image = serializers.ImageField(label=‘图片‘, required=False)
Serializer(instance=None, data=empty, **kwarg)
serializer = AccountSerializer(account, context={‘request‘: request})
from booktest.models import BookInfo
book = BookInfo.objects.get(id=2)
from booktest.serializers import BookInfoSerializer
serializer = BookInfoSerializer(book)
serializer.data
# {‘id‘: 2, ‘btitle‘: ‘天龙八部‘, ‘bpub_date‘: ‘1986-07-24‘, ‘bread‘: 36, ‘bcomment‘: 40, ‘image‘: None}
book_qs = BookInfo.objects.all()
serializer = BookInfoSerializer(book_qs, many=True)
serializer.data
# [OrderedDict([(‘id‘, 2), (‘btitle‘, ‘天龙八部‘), (‘bpub_date‘, ‘1986-07-24‘), (‘bread‘, 36), (‘bcomment‘, 40), (‘image‘, N]), OrderedDict([(‘id‘, 3), (‘btitle‘, ‘笑傲江湖‘), (‘bpub_date‘, ‘1995-12-24‘), (‘bread‘, 20), (‘bcomment‘, 80), (‘image‘ne)]), OrderedDict([(‘id‘, 4), (‘btitle‘, ‘雪山飞狐‘), (‘bpub_date‘, ‘1987-11-11‘), (‘bread‘, 58), (‘bcomment‘, 24), (‘ima None)]), OrderedDict([(‘id‘, 5), (‘btitle‘, ‘西游记‘), (‘bpub_date‘, ‘1988-01-01‘), (‘bread‘, 10), (‘bcomment‘, 10), (‘im‘, ‘booktest/xiyouji.png‘)])]
hbook = serializers.PrimaryKeyRelatedField(label=‘图书‘, read_only=True)
或
hbook = serializers.PrimaryKeyRelatedField(label=‘图书‘, queryset=BookInfo.objects.all())
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label=‘ID‘, read_only=True)
btitle = serializers.CharField(label=‘名称‘, max_length=20)
bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
bread = serializers.IntegerField(label=‘阅读量‘, required=False)
bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
image = serializers.ImageField(label=‘图片‘, required=False)
from booktest.serializers import BookInfoSerializer
data = {‘bpub_date‘: 123}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # 返回False
serializer.errors
# {‘btitle‘: [ErrorDetail(string=‘This field is required.‘, code=‘required‘)], ‘bpub_date‘: [ErrorDetail(string=‘Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].‘, code=‘invalid‘)]}
serializer.validated_data # {}
?
data = {‘btitle‘: ‘python‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # True
serializer.errors # {}
serializer.validated_data # OrderedDict([(‘btitle‘, ‘python‘)])
# Return a 400 response if the data was invalid.
serializer.is_valid(raise_exception=True)
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
def create(self, validated_data):
"""新建"""
return BookInfo(**validated_data)
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
instance.btitle = validated_data.get(‘btitle‘, instance.btitle)
instance.bpub_date = validated_data.get(‘bpub_date‘, instance.bpub_date)
instance.bread = validated_data.get(‘bread‘, instance.bread)
instance.bcomment = validated_data.get(‘bcomment‘, instance.bcomment)
return instance
?
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...
def create(self, validated_data):
"""新建"""
return BookInfo.objects.create(**validated_data)
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
instance.btitle = validated_data.get(‘btitle‘, instance.btitle)
instance.bpub_date = validated_data.get(‘bpub_date‘, instance.bpub_date)
instance.bread = validated_data.get(‘bread‘, instance.bread)
instance.bcomment = validated_data.get(‘bcomment‘, instance.bcomment)
instance.save()
return instance
book = serializer.save()
from db.serializers import BookInfoSerializer
data = {‘btitle‘: ‘封神演义‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # True
serializer.save() # <BookInfo: 封神演义>
from db.models import BookInfo
book = BookInfo.objects.get(id=2)
data = {‘btitle‘: ‘倚天剑‘}
serializer = BookInfoSerializer(book, data=data)
serializer.is_valid() # True
serializer.save() # <BookInfo: 倚天剑>
book.btitle # ‘倚天剑‘
serializer.save(owner=request.user)
# Update `comment` with partial data
serializer = CommentSerializer(comment, data={‘content‘: u‘foo bar‘}, partial=True)
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta: # Meta是一个内部类,它用于定义一些Django模型类的行为特性
model = BookInfo
fields = ‘__all__‘
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘)
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
exclude = (‘image‘,)
class HeroInfoSerializer2(serializers.ModelSerializer):
class Meta:
model = HeroInfo
fields = ‘__all__‘
depth = 1
HeroInfoSerializer():
id = IntegerField(label=‘ID‘, read_only=True)
hname = CharField(label=‘名称‘, max_length=20)
hgender = ChoiceField(choices=((0, ‘male‘), (1, ‘female‘)), label=‘性别‘, required=False, validators=[<django.core.valators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
hcomment = CharField(allow_null=True, label=‘描述信息‘, max_length=200, required=False)
hbook = NestedSerializer(read_only=True):
id = IntegerField(label=‘ID‘, read_only=True)
btitle = CharField(label=‘名称‘, max_length=20)
bpub_date = DateField(allow_null=True, label=‘发布日期‘, required=False)
bread = IntegerField(label=‘阅读量‘, max_value=2147483647, min_value=-2147483648, required=False)
bcomment = IntegerField(label=‘评论量‘, max_value=2147483647, min_value=-2147483648, required=False)
image = ImageField(allow_null=True, label=‘图片‘, max_length=100, required=False)
class HeroInfoSerializer(serializers.ModelSerializer):
hbook = BookInfoSerializer()
class Meta:
model = HeroInfo
fields = (‘id‘, ‘hname‘, ‘hgender‘, ‘hcomment‘, ‘hbook‘)
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘, ‘bread‘, ‘bcomment‘)
read_only_fields = (‘id‘, ‘bread‘, ‘bcomment‘)
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘, ‘bread‘, ‘bcomment‘)
extra_kwargs = {
‘bread‘: {‘min_value‘: 0, ‘required‘: True},
‘bcomment‘: {‘min_value‘: 0, ‘required‘: True},
}
# BookInfoSerializer():
# id = IntegerField(label=‘ID‘, read_only=True)
# btitle = CharField(label=‘名称‘, max_length=20)
# bpub_date = DateField(allow_null=True, label=‘发布日期‘, required=False)
# bread = IntegerField(label=‘阅读量‘, min_value=2147483647, min_value=0, required=True)
# bcomment = IntegerField(label=‘评论量‘, min_value=2147483647, min_value=0, required=True)
标签:active lin set 执行 save operator 特性 response 调用
原文地址:https://www.cnblogs.com/liudemeng/p/9495239.html