首页 > 解决方案 > 有没有办法在 django 序列化程序中获取请求数据?

问题描述

这是我正在获取一些 query_params 的示例视图,我想在序列化程序中访问它,我将在此视图中相应地使用它。

class SomeApi(APIView):
    def get(self, request):
        username = request.query_params.get('username')
        page = request.query_params.get('page')
        phone = request.query_params.get('phone')
        if username and page and phone:
            return Response({'message':'some message'}, status=status.HTTP_200_OK)
        return Response({'message':'error'}, status=status.HTTP_400_BAD_REQUEST) 

这是一个示例序列化程序,我想在其中获取 query_param 电话(如果可用)并编写一些逻辑来返回一个额外的方法字段。

class SomeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Some
        fields = '__all__'

    def get_isPhone(self, obj):
        phone = ??? #HERE I WANT TO GET phone query_params which is passed in API call
        if phone:
            return phone
        else:
            return 0

标签: pythondjangoserializationdjango-rest-frameworkdjango-serializer

解决方案


如果我正确理解您的问题,您应该使用传入数据创建序列化程序,然后is_valid()在您的序列化程序上尝试方法,使用时有特定的钩子is_valid(),您可以在验证之前访问您的数据,在您的情况下,我认为您应该使用to_internal_value()

def to_internal_value(self, data):
    # here is the first place to manipulate data you can do what ever you want with 
    #your data          
    return super().to_internal_value(data) 

推荐阅读