gpt4 book ai didi

python - Django Rest 框架序列化程序关系 : How to get a list of only the latest track?

转载 作者:行者123 更新时间:2023-12-02 14:58:52 27 4
gpt4 key购买 nike

我正在关注此文档 here .我正在努力解决能够查询 Album 对象并让它只返回最新轨道而不是返回所有轨道的问题。以下是文档模型和序列化程序的修改版本。

模型

class AlbumOwner(models.Model):
username = models.CharField(max_length=100)

class Album(models.Model):
album_name = models.CharField(max_length=100)
owner = models.ForeignKey(AlbumOwner, related_name='owner', on_delete=models.CASCADE)

class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)

class Meta:
get_latest_by = 'created_at'

序列化器

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

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

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

我目前使用的查询如下,“o”代表所有者:

albums = Album.objects.filter(owner=o)
serializer = AlbumSerializer(albums)
serializer.data

Serializer.data 将返回类似这样的响应:

[{
'album_name': 'The Grey Album',
'tracks': [
{'title': 'Public Service Announcement', "created_at": "2018-06-15T06:22:35.680291Z"},
{'title': 'What More Can I Say', "created_at": "2014-07-15T06:22:35.680291Z"},
{'title': 'Encore', "created_at": "2016-07-15T06:22:35.680291Z"}
],
},{
'album_name': 'The Blue Album',
'tracks': [
{'title': 'PSA', "created_at": "2002-07-15T06:22:35.680291Z"},
{'title': 'WMCIS', '"created_at": "2003-07-15T06:22:35.680291Z"},
{'title': 'E', "created_at": "2005-07-15T06:22:35.680291Z"}
],
},
]

我想要的响应是只返回最新日期的轨道:

[{
'album_name': 'The Grey Album',
'tracks': [
{'title': 'Public Service Announcement', "created_at": "2018-06-15T06:22:35.680291Z"}
],
},{
'album_name': 'The Blue Album',
'tracks': [
{'title': 'E', "created_at": "2005-07-15T06:22:35.680291Z"}
],
},
]

最佳答案

尝试类似下面的操作,即分割轨道查询集或根据某些过滤器选择最新的轨道。

class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SerializerMethodField()

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

def get_tracks(self, album):
qs = album.tracks.all()[-1:]
return TrackSerializer(qs, many=True, read_only=True).data

关于python - Django Rest 框架序列化程序关系 : How to get a list of only the latest track?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51348982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com