在Django中,写后台Rest的api接口,希望前端调用时支持
is_audio=true
is_audio=false
不传递is_audio
后台可以正常解析为bool类型变量
以便于送到后续的gridfs的mongo中去find
相关已有代码是:
class MongoDBGridFsFiles(APIView): permission_classes = (AllowAny, ) def get(self, request): search = request.query_params.get('search', '') is_audio = request.query_params.get('is_audio', None) # true / false/ not_pass resource_type = request.query_params.get('resource_type', '') # storybook / song / not_pass gridfs_query = {} if search: gridfs_query["filename"] = {"$regex": search, "$options": "i"} if is_audio: is_audio_lower = is_audio.lower() if is_audio_lower == "true": is_audio_bool = True else: is_audio_bool = False gridfs_query["metadata.fileInfo.isAudio"] = is_audio_bool if resource_type: gridfs_query["metadata.resourceType"] = resource_type file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find(gridfs_query)]
希望此处可以request.query_params.get直接自动识别为is_audio为bool,而不是字符串
搜:
django query string boolean
django boolean query param in GET
django API bool query parameter
django request.query_params.get bool
django request query_params get boolean
【总结】
结果真的没有什么好办法,就是把字符串转换为bool
前端调用:
http://localhost:65000/api/v1/mongodb_gridfs_files/?is_audio=true&resource_type=song&search=ani
后端解析:
search = request.query_params.get('search', '') is_audio = request.query_params.get('is_audio', None) # true / false/ not_pass resource_type = request.query_params.get('resource_type', '') # storybook / song / not_pass logger.info("search=%s,is_audio=%s,resource_type=%s", search, is_audio, resource_type) gridfs_query = {} if search: gridfs_query["filename"] = {"$regex": search, "$options": "i"} if is_audio: is_audio_lower = is_audio.lower() if is_audio_lower == "true": is_audio_bool = True else: is_audio_bool = False logger.info("is_audio_bool=%s", is_audio_bool) gridfs_query["metadata.fileInfo.isAudio"] = is_audio_bool if resource_type: gridfs_query["metadata.resourceType"] = resource_type logger.info("gridfs_query=%s", gridfs_query) file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find(gridfs_query)]
log输出:
INFO|20180809 16:00:41|views:get:832|search=ani,is_audio=true,resource_type=song INFO|20180809 16:00:41|views:get:844|is_audio_bool=True INFO|20180809 16:00:41|views:get:850|gridfs_query={'filename': {'$regex': 'ani', '$options': 'i'}, 'metadata.fileInfo.isAudio': True, 'metadata.resourceType': 'song'}
转载请注明:在路上 » 【已解决】Django中如何传递和获取获取查询布尔类型参数