django query模块
作者:二十一 时间:2021-12-01 09:16:22
最近在接触一个Django项目,使用的是fbv( function-base views )
模式,看起来特别不舒服,项目中有一个模型类117个字段,看我的有点晕,不过还是得干呀,生活呀,头发呀。
个人觉得这个模块用处不是很大,并且写的也不是很好。看了看源码如此简单,就给大家分享一下,也好久没有给大家分享东西了。
import json
def get_default_valcastfunc(val_cast_type=None):
"""通过一下方法传入的字符串判断使用哪种数据返回"""
if val_cast_type == 'int':
return 0, int
elif val_cast_type == 'listjson':
return '[]', json.loads
elif val_cast_type == 'dictjson':
return '{}', json.loads
return None, None
def get_query_value(request, key, default=None, val_cast_func=None, val_cast_type=None):
""" 通过val_cast_type获取到优化数据的函数,或者通过val_cast_func函数传入val """
if val_cast_type in ['int', 'listjson', 'dictjson']:
default, val_cast_func = get_default_valcastfunc(val_cast_type)
value = request.POST.get(key) or request.GET.get(key) or default
return val_cast_func(value) if val_cast_func else (value or '')自认为的几个重点
request.POST.get
这样取值即使key不存在也不会报错,而是返回None,而request.POST[key]
这样会报错KeyError ,GET同POST Django的模型类使用get若无值,则会报错。
在返回的时候使用参数val_cast_func
,而val_cast_func
并未传入,而是通过get_default_valcastfunc
返回设置
来源:https://segmentfault.com/a/1190000018946742
标签:django,query,模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MYSQL的DATE_FORMAT()格式化日期
2009-02-27 16:04:00
MySql 随机取N条数据
2009-03-17 12:46:00
关于mysql与mysqli
2011-02-23 12:03:00
php curl登陆qq后获取用户信息时证书错误
2023-11-15 08:23:39
Python+Opencv实现图像匹配功能(模板匹配)
2022-06-28 08:56:35
![](https://img.aspxhome.com/file/2023/3/98933_0s.jpg)
Python+django实现文件上传
2022-08-31 20:52:22
python爬取哈尔滨天气信息
2023-12-10 22:28:05
Python使用Pandas处理测试数据的方法
2021-12-18 10:47:18
![](https://img.aspxhome.com/file/2023/3/81583_0s.png)
Python计算点到直线距离、直线间交点夹角
2022-09-05 10:27:04
![](https://img.aspxhome.com/file/2023/2/87982_0s.jpg)
跟老齐学Python之画圈还不简单吗?
2022-06-07 04:57:11
![](https://img.aspxhome.com/file/2023/2/77022_0s.png)
Python实现自动化域名批量解析分享
2023-01-27 00:04:36
![](https://img.aspxhome.com/file/2023/2/75172_0s.png)
ASP编程代码:隐藏图片的真实地址
2008-10-19 17:14:00
Python判断某个用户对某个文件的权限
2023-12-15 01:25:27
python学习之第三方包安装方法(两种方法)
2021-02-20 03:29:40
![](https://img.aspxhome.com/file/2023/4/99014_0s.png)
Python中装饰器的基本功能理解
2021-05-26 05:17:56
python实现滑雪游戏
2021-10-08 05:20:35
面向对象设计过程中必须遵守的相关准则
2009-01-08 15:52:00
ASP正则获取图片地址
2009-09-03 13:18:00
python3+selenium自动化测试框架详解
2022-01-29 18:26:01
![](https://img.aspxhome.com/file/2023/7/75897_0s.png)
对pandas中iloc,loc取数据差别及按条件取值的方法详解
2021-06-15 01:58:05