class SongsSerializer(serializers.ModelSerializer):
artist_name = Artist.objects.name
genre_name = Genre.objects.name
class Meta:
model = Song
fields = [
'pk',
'album',
'art',
'title',
'song',
'artist',
'slug',
'genre',
]
read_only_fields = ['id']
Serializer.py
所以有3种类型的模型类,每种都有一些外键关系
class Song(models.Model):
album = models.ForeignKey(Album,on_delete=models.CASCADE)
title = models.CharField(max_length=250)
song = models.FileField(upload_to='songs')
slug = models.SlugField(max_length=250,default='')
genre = models.ForeignKey(Genre,on_delete=models.CASCADE)
artist = models.ForeignKey(Artist,on_delete=models.CASCADE)
API的JSON响应是:
{pk: 1, album: 1, art: "http://localhost:8000/media/art_music/pp_PAgznjI.jpg", title: "Test", song: "http://localhost:8000/media/songs/Daaru_Band_-_Mankirt_Aulakh_DJJOhAL.Com_CtS7TAv.mp3", …}
与其将Artist and Genre显示为1,还应显示专辑,Artist and Genre的名称
答案 0 :(得分:0)
只需为您的ForeignKey使用序列化器,它们也需要序列化。如果您忘记了id
中只有ForeignKey
会被序列化。
class SongsSerializer(serializers.ModelSerializer):
artist = ArtistSerializer()
class Meta:
model = Song
fields = [
'pk',
'album',
'art',
'title',
'song',
'artist',
'slug',
'genre',
]
read_only_fields = ['id']
class ArtistSerializer(serializers.ModelSerializer):
fields = [
'pk',
'name'
]