传递额外的参数到Django Rest Framework中的嵌套Serializer
我有这样的序列化器:
class FirstModelSerializer(serializers.ModelSerializer):
secondModel = SecondModelSerializer()
class Meta:
model = FirstModel
fields = '__all__'
其中secondModel是FirstModel的ManyToMany字段.
有什么办法可以将FirstModel对象ID传递给SecondModelSerializer?
最佳答案
那比我想的容易.我只需要使用这样的上下文
class FirstModelSerializer(serializers.ModelSerializer):
secondModel = SerializerMethodField()
class Meta:
model = FirstModel
fields = '__all__'
def get_secondModel(self, obj):
return SecondModelSerializer(obj.secondModel.all(), many=True, context={'first_model_id': obj.id)).data
并在SecondModelSerializer中使用self.context.get(‘first_model_id’)来获取此ID.