说我的序列化程序看起来像这样
class EntitySerializer(serializers.ModelSerializer):
entity_instance = EntityInstanceSerializer(many=True)
tags = EntityTagSerializer(many=True)
class Meta:
model = Entity
fields = ('id', 'entity_instance', 'tags', 'note', 'source')
class EntityTagSerializer(serializers.ModelSerializer):
class Meta:
model = EntityTagLabel
fields = ('entity_tag_label',)
我的代码模型如下所示:
class EntityTag(models.Model):
entity_tag_label = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.entity_tag_label
现在这很好,但是我的回答是这样的:
...
"tags": [
{
"entity_tag_label": "SENDER"
}
],
我的标签序列化器是否可以简单地返回每个标签的字符串表示?这样我就会
"tags": [
"Sender",
],
作为例子
答案 0 :(得分:2)
您可以使用SlugRelatedField执行此操作。类似的东西:
class EntitySerializer(serializers.ModelSerializer):
entity_instance = EntityInstanceSerializer(many=True)
tags = serializers.SlugRelatedField(
slug_field='entity_tag_label',
many=True,
read_only=True
)
class Meta:
model = Entity
fields = ('id', 'entity_instance', 'tags', 'note', 'source')