有没有办法订购嵌套序列化
_set
,例如订购
pk
或
time-stamp
。
所以基本上顺序
song_set
下面的 json 数据显示从最近到最新创建的对象,在本例中为
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)
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'
原文由 laa 发布,翻译遵循 CC BY-SA 4.0 许可协议