Django DRF ListField以反序列化GET的queryparams中的ID列表 [英] Django DRF ListField to deserialize list of ids in GET's queryparams
问题描述
尝试使用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 /?应用程序=一,二,三
p>
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})
所有我看到的是 -
All I see is this -
{
"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
此外,您的服务器将作为数组接收应用程序,即应用程序[]
而不是应用程序
。
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的queryparams中的ID列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!