问题描述
尝试使用 DRF 的 ListField 选项反序列化查询参数中的值列表(以下示例中的应用程序).我很难让它工作.无法在网络上找到示例.希望有人帮忙.
Tried to use DRF's ListField option to de-serialize list of values (applications in the example below) in query params. I'm having trouble making it work. Couldn't find with examples in the web. Hoping someone to throw some help.
api:/getAppStats/?applications=one,two,three
class MySerializer(serializers.Serializer):
applications = serializers.ListField(child=serializers.CharField())
start_date = serializers.DateField(default=(datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat())
end_date = serializers.DateField(default=datetime.datetime.utcnow().date().isoformat())
class SomeView(generics.GenericAPIView):
"""
"""
permission_classes = [AllowAny]
serializer_class = MySerializer
def get(self, request, *args, **kwargs):
"""
Just return query params..
"""
serializer = MySerializer(data=request.query_params)
if not serializer.is_valid():
return Response({'stats':'invalid input data'})
return Response({'stats':serializer.data})
我看到的只有这个 -
{
"stats": {
"applications": [],
"start_date": "2015-05-27",
"end_date": "2015-06-26"
}
}
我是否以错误的方式发送了输入参数?我错过了一些小事吗?
Am I sending the input params in incorrect way? Did I miss something trivial?
谢谢!
推荐答案
为同一个键发送多个参数的标准方法是两次使用相同的键名.
The standard approach to send multiple parameters for same key is is to use the same key name twice.
你可以这样做:
/getAppStats/?applications=one&applications=two&applications=three
此外,您的服务器将以数组的形式接收应用程序,即作为 applications[]
而不是 applications
.
Also, your server will receive the applications as an array i.e. as applications[]
and not applications
.
class SomeView(generics.GenericAPIView):
"""
"""
permission_classes = [AllowAny]
serializer_class = MySerializer
def get(self, request, *args, **kwargs):
"""
Just return query params..
"""
# get the applications list
applications = request.query_params.getlist('applications[]')
# create a dictionary and pass it to serializer
my_data = {'applications': applications, ...}
serializer = MySerializer(data=my_data)
if not serializer.is_valid():
return Response({'stats':'invalid input data'})
return Response({'stats':serializer.data})
这篇关于Django DRF ListField 反序列化 GET 的查询参数中的 id 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!