python - 有没有办法在 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
解决方案
如果我正确理解您的问题,您应该使用传入数据创建序列化程序,然后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)
推荐阅读
- qt - 如何在标签中使用 Text.ElideMiddle?
- php - Laravel redirect()->action 不起作用并显示缺少的参数
- matlab - 如何从 Matlab 中的 ode45 获取特定 t 值的 y 和 y' 值?
- c++ - 为什么 sizeof(ar)/ sizeof(ar[0]) 在传递给函数时不能在向量上正常工作?
- javascript - 试图“映射”嵌套的 JSON 元素对象(javascript)
- javascript - 找到要在括号字符串的开头或结尾添加的最小括号以使其平衡
- javascript - 当函数声明和函数表达式同名时,为什么要调用函数表达式?
- python-3.x - 如何使用 python 的 gspread wks.update_cells 更新谷歌电子表格中的单元格
- php - 使用 slim 框架在 php 中显示唯一的数组数据
- python - 带有保持额外价值的条件的python格式选项