嗨,我想只提供对值不会对REST服务键:
拿上我的serializers.py看看:
class TranslationSerializer(serializers.ModelSerializer):
translated_term = serializers.CharField(read_only=True)
class Meta:
model = Translation
fields = ('language','translated_term')
class VocabSerializer(serializers.ModelSerializer):
...
translates = TranslationSerializer(many=True, read_only=True)
...
class Meta:
model = Vocab
fields = ( ..., 'translates',...)
结果如下:
"translates": [
{
"language": "EN",
"translated_term": "Chair"
}
{
"language": "IT",
"translated_term": "asd"
}
],
你可以看到这个结果表明,该字段旁边字段的值字典键的名称。 但我想有不同的结构。 像下面这样:
"translates": [
{
"EN": "Chair", "IT":"asd"
}
],
这个例子示出了对键/值,其中键是语言字段值和字典的值是翻译的字段的值。
我怎么能只显示对与“翻译”场“语言”字段的值,而不字段的名称?
您可以通过定制实现它列表串行 :
class TranslationListSerializer(serializers.ListSerializer):
def to_representation(self, data):
r = super().to_representation(data)
return { item['language']: item['translated_term'] for item in r }
class TranslationSerializer(serializers.ModelSerializer):
translated_term = serializers.CharField(read_only=True)
class Meta:
model = Translation
fields = ('language','translated_term')
list_serializer_class = TranslationListSerializer
通过创建自定义to_representation的串行功能,你可以在你的字典表示控制。
class TranslationSerializer(serializers.ModelSerializer):
translated_term = serializers.CharField(read_only=True)
def to_representation(self, instance):
# get the instance -> Dict of primitive data types
representation = super(TranslationSerializer, self).to_representation(instance)
# manipulate returned dictionary as desired
language = representation.pop('language')
translated_term = representation.pop('translated_term')
# repackage
repackaged = {language: translated_term}
return repackaged
class Meta:
model = Translation
fields = ('language','translated_term')
这将在格式生成JSON
"translates": [
{
"EN": "Chair"
},
"IT": "asd"
}
],
但是,你怎么希望它看起来,也许是VocabSerializer自定义“to_representation”可以瓶坯,这是不完全的。
文章来源: Django Rest Framework custom field only pair of values (without fieldname as dict key)