serializers--嵌套关系作为字段来表示

参考官网:https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

先建立model

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 __str__(self):
        return '%d: %s' % (self.order, self.title)

 

嵌套关系可以通过使用序列化器作为字段来表示。

如果该字段用于表示to-many关系(意思是:外键在另外一个model,不懂的话,下面例子会补充),则应该将many=True标志添加到序列化器字段中。

 

如下ModelSerializer序列化:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True) #刚才上面说的就是这里,外键在Track上,不知道你懂不懂

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

 

默认情况下,嵌套序列化器是只读的。如果希望支持对嵌套序列化器字段的写操作,则需要创建create()和/或update()方法,以便显式指定应该如何保存子关系。

如果要实现可写,就要去掉read_only=true,同时添加create方法,如下:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

    def create(self, validated_data): 
        tracks_data = validated_data.pop('tracks')
        album = Album.objects.create(**validated_data)
        for track_data in tracks_data:
            Track.objects.create(album=album, **track_data)
        return album
#必须有create,才能使用save(), data={...} ,比如: 
a=IdcSerializer(data=data)
a.save()

 

posted @ 2019-07-05 16:11  凯文队长  阅读(602)  评论(0编辑  收藏  举报