我想覆盖序列化程序的to_representation
. 如何在其中传递请求对象以便构建 url?
class FooSerializer(serializers.ModelSerializer):
name = serializers.StringRelatedField()
link = serializers.SerializerMethodField()
class Meta:
model = Foo
fields = ('name', 'link')
def to_representation(self, instance):
request = self.context.get('request') # Get request here
return {'foo': request.build_absolute_uri(
'/apps/foo/{}'.format(
object.id))
}