From ef779f759008ddc317f45c89df65c87504c624af Mon Sep 17 00:00:00 2001 From: RogerWork Date: Mon, 13 Nov 2023 18:14:18 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=96=B0=E5=AD=A6=E4=B9=A0serializer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/music/serializer.py | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/apps/music/serializer.py b/apps/music/serializer.py index 031f073..551789b 100644 --- a/apps/music/serializer.py +++ b/apps/music/serializer.py @@ -3,13 +3,43 @@ from rest_framework import serializers, fields from apps.music.models import * -class AlbumSerializer(serializers.ModelSerializer): - class Meta: - model = Album - fields = ('id', 'artist', 'name', 'release_date', 'num_stars') +class AlbumSerializer(serializers.Serializer): + # 设置外键PrimaryKeyRelatedField + artist = serializers.PrimaryKeyRelatedField(label='音乐家', queryset=Musician.objects.all(), many=False, + allow_null=False) + name = serializers.CharField(label='专辑名', required=True, max_length=10) + # 修改字段名称并映射数据模型字段,source为指定模型的字段的字符串形式 + publish_date = serializers.DateField(label='发行日期', required=False, source='Album.release_date') + num_stars = serializers.IntegerField(label='好评度') + + +class MusicianSerializer(serializers.Serializer): + first_name = serializers.CharField(max_length=20, required=True) + last_name = serializers.CharField(max_length=20, required=True) + instrument = serializers.CharField(max_length=50) + # 根据外键的关联关系,将AlbumNameSerializer做为扩展信息 + album_musician = AlbumSerializer(many=True) + + # 重写create方法 + def create(self, validated_data): + albums_data = validated_data.pop('album_musician') + musician = Musician.objects.create(**validated_data) + # 插入专辑数据,artist为上一步中插入后返回的对象 + for album in albums_data: + Album.objects.create(artist=musician, **album) + return musician + + def update(self, instance, validated_data): + pass + + +# class AlbumModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = Album +# fields = ('id', 'artist', 'name', 'release_date', 'num_stars') -class MusicianSerializer(serializers.ModelSerializer): +class MusicianModelSerializer(serializers.ModelSerializer): # album_musician = AlbumSerializer(read_only=True, many=True) # 定义只读外键字段后在fields中添加此键 album_musician = AlbumSerializer(many=True) # 定义只读外键字段后在fields中添加此键,如果需要写入create和update方法,则不应设置readonly