假设在ModelSerializer
类以下
class UserSongSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
song_likes = serializers.ReadOnlyField() # This is model's property field
song_shares = serializers.ReadOnlyField()
song_plays = serializers.ReadOnlyField()
song_price = serializers.ReadOnlyField()
genre = GenreSerializer(many=True,required=False,context={'key':5})
language = LanguageSerializer(many=True, required=False)
像下面那样传递特定的context
kwarg
genre = GenreSerializer(many=True,required=False,context={'fields':['name']})
由于在某些特定情况下,我只想检索Genre
模型类中的名称字段,因此我重写了GenreSerializer
类的get_fields_name
方法,以便仅在需要通过上下文时提及特定字段
class GenreSerializer(serializers.ModelSerializer):
def get_field_names(self, *args, **kwargs):
"""
Overriding ModelSerializer get_field_names method for getting only specific fields in serializer when mentioned in SerializerClass arguments
"""
field_names = self.context.get('fields', None)
if field_names:
return field_names
return super(GenreSerializer, self).get_field_names(*args, **kwargs)
class Meta:
model = Genre
fields = '__all__'
但是,我无法在覆盖的None
方法中获取任何“字段”(获取get_fields_name
)键。我知道其他方式以及使用StringRelatedField
的方式,但这会将输出表示形式更改为
"genre":[
"Pop",
"Rock"
]
鉴于此,我想坚持我的原始表示方式
"genre": [
{
"id": 3,
"name": "Pop",
"created_date": "2018-09-05T17:05:59.705422+05:30",
"updated_date": "2018-09-20T14:43:02.062107+05:30",
"status": false
},
{
"id": 4,
"name": "Rock",
"created_date": "2018-09-05T17:06:06.889047+05:30",
"updated_date": "2018-09-17T16:45:22.684044+05:30",
"status": true
},
{
"id": 5,
"name": "Classical",
"created_date": "2018-09-05T17:06:14.216260+05:30",
"updated_date": "2018-09-05T17:06:14.275082+05:30",
"status": true
}
]
更新-我想要的是这样
"genre": [
{
"name": "Pop"
},
{
"name": "Rock"
},
{
"name": "Classical"
}
]
答案 0 :(得分:1)
只能将上下文设置为根串行器。
每当实例化UserSongSerializer
时,它将覆盖嵌套的genre
上下文。
如果您使用的是通用视图,则需要覆盖视图的get_serializer_context
并在其中添加自己的上下文。已记录at the bottom of the methods section
PS:上下文与序列化器,字段,验证器“共享”。
PPS:设置好上下文后,请不要更改上下文,这将是不确定的行为。