cod*_*y46 2 python django-rest-framework
模型:
class Genre(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Song(models.Model):
name = models.CharField(max_length=200)
genre = models.ManyToManyField(Genre)
Run Code Online (Sandbox Code Playgroud)
序列化器:
class GenreSerializer(serializers.ModelSerializer):
class Meta:
model = Genre
fields = '__all__'
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = '__all__'
def to_representation(self, instance):
rep = super().to_representation(instance)
print(GenreSerializer(instance.name).data)
return rep
Run Code Online (Sandbox Code Playgroud)
序列化程序中的上述打印给出: {'name': None} 并且响应使用流派 ID 而不是值:
[
{
"id": 1,
"name": "Abcd",
"genre": [
1,
3
]
}
]
Run Code Online (Sandbox Code Playgroud)
其中流派1. 流行,3. 摇滚
我可以对 to_representation 进行哪些更改以打印值而不是流派的 id,流派是具有歌曲模型的 ManyToManyField。
你就快到了,试试这个
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = '__all__'
def to_representation(self, instance):
rep = super().to_representation(instance)
rep["genre"] = GenreSerializer(instance.genre.all(), many=True).data
return repRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2987 次 |
| 最近记录: |