1,在serializer.save的时候要加入新的内容
save时,在request.data内容不够的情况下加入新的内容,
serializer.save(owner=request.user)
2,限制,报错
def multiple_of_ten(value): if value % 10 != 0: raise serializers.ValidationError('Not a multiple of ten') class GameRecord(serializers.Serializer): score = IntegerField(validators=[multiple_of_ten])
3,更新原有数据
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
4,序列化套序列化
class UserSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField(max_length=100) class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False
) #required=False表示可以为空 #many=True 表示接受多个值为list.
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
5,create
class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user
6,关系型序列化
class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title)
StringRelatedField
class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks')
==> 由于前面的__unicode__方法把两个结合在一起,并且设置了many=True,所以会有多个值
{ 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act', ... ] }
PrimaryKeyRelatedField
class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks')
{ 'album_name': 'Undun', 'artist': 'The Roots', 'tracks': [ 89, 90, 91, ... ] }
参数:
queryset 指定关联的queryset,可以进行一些排除操作
many 可以指定多个数据,并且返回的数据格式为列表
allow_null 是否允许为空
pk_field 指定主键为唯一字段
SlugRelatedField
class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) class Meta: model = Album fields = ('album_name', 'artist', 'tracks')
==>返回的是slug_field指定的字段
{
'album_name': 'Dear John',
'artist': 'Loney Dear',
'tracks': [
'Airport Surroundings',
'Everything Turns to You',
'I Was Only Going Out',
...
]
}
字段属性:
slug_field :指定关联表的某个属性
queryset 指定集合
many 指多个
allow_null 是否可为空
RelatedField
import time class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks')
==> RelatedField字段分析了,重新定义to_representation方法,内部的value是实例对象
{ 'album_name': 'Sometimes I Wish We Were an Eagle', 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', 'Track 3: The Wind and the Dove (04:34)', ... ] }