python – Django Rest-Framework嵌套序列化器命令

前端之家收集整理的这篇文章主要介绍了python – Django Rest-Framework嵌套序列化器命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法订购嵌套的序列化器_set,例如按pk或时间戳排序.

因此,基本上将json数据中显示的song_set从最相邻的最新对象创建,在本例中为order_by(‘ – timestamp’)或order_by(‘ – pk’).

Json数据

{
    "pk": 151,"album_name": "Name","song_set": [
         {
           pk: 3,timestamp: '5 seconds'
         },{
           pk: 2,timestamp: '10 seconds'
         },{
           pk: 1,timestamp: '15 seconds'
         }
    ]
}

模型

class Album(models.Model):
    album_name     = models.CharField(max_length=100,blank=True)


class Song(models.Model):
    album          = models.ForeignKey('album.Album',default=1)
    timestamp      = models.DateTimeField(auto_now_add=True,auto_now=False)

Searilizer

class SongListSerializer(HyperlinkedModelSerializer):
    class Meta:
        model = Song
        fields = [
            'pk','timestamp'
        ]

class AlbumSerializer(HyperlinkedModelSerializer):
    song_set = SongListSerializer(many=True,read_only=True)
    class Meta:
        model = Album
        fields = [
            'pk','timestamp','song_set'
        ]

解决方法

您可以使用SerializerMethodField并为此编写自定义方法.
class AlbumSerializer(HyperlinkedModelSerializer):
    song_set = serializer.SerializerMethodField()
    class Meta:
        model = Album
        fields = [
            'pk','song_set'
        ]

    def get_song_set(self,instance):
        songs = instance.song_set.all().order_by('-timestamp')
        return SongListSerializer(songs,many=True).data

猜你在找的Python相关文章