我需要使用请求参数返回一些计算值。 看来我需要从ModelSerializer内部访问请求参数。 我该怎么办?
class PostSerializer(serializers.ModelSerializer):
owner = UserSerializer()
spot = SpotSerializer()
is_login_user_favorite = serializers.SerializerMethodField()
class Meta:
model = Post
fields = '__all__'
read_only_fields = ('owner',)
def get_is_login_user_favorite(self, validated_date):
return True # I need change this dynamically
class PostListAPIView(generics.ListAPIView):
serializer_class = serializers.PostSerializer
queryset = Post.objects.all().order_by('-pk')
permission_classes = [IsAuthenticated]
答案 0 :(得分:1)
您可以通过context
访问它。像这样:
class PostSerializer(serializers.ModelSerializer):
...
def get_is_login_user_favorite(self, validated_date):
request = self.context['request'] # <-- Here
....
return value # I need change this dynamically
基本上,当您使用Generic API Views
时,请求会通过上下文自动发送到序列化器。 methods section(at the bottom named as 'other methods')
文档中也对此进行了解释。