【发布时间】:2018-12-01 01:02:42
【问题描述】:
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']
序列化器.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 和 Genre 显示为 1,而应显示专辑名称、Artist 和 Genre
【问题讨论】:
标签: python django rest django-models django-rest-framework