from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ['field1', 'field2']
def to_representation(self, instance):
# 從context中獲取額外的引數
extra_param = self.context.get('extra_param')
# 使用extra_param進行額外的處理
# ...
# 呼叫父類的to_representation方法
data = super().to_representation(instance)
# 根據需要,可以使用extra_param修改data
# ...
return data
# 在檢視中使用序列化器時傳入context
def my_view(request):
queryset = MyModel.objects.all()
serializer = MyModelSerializer(queryset, many=True, context={'extra_param': 'some_value'})
return Response(serializer.data)