django q 对象条件匹配
我的问题是,当我选择 datefrom 和 dateto 时,它显示错误。“在中找不到关键‘性别’
现在即使我使用 Q 对象仍然存在与之前相同的问题..
search_gender = request.POST["gender"]
age_from = request.POST["age_from"]
age_to = request.POST["age_to"]
date_from = request.POST["date_from"]
date_to = request.POST["date_to"]
if date_from:
date_from = datetime.strptime(request.POST["date_from"],"%d %B %Y")
if date_to:
date_to = datetime.strptime(request.POST["date_to"],"%d %B %Y")
patient = PatientInfo()
p_male = 0
p_female = 0
age1 = 0
age2 = 0
date1 = 0
date2 = 0
if search_gender == 'male' :
p_male = 1
if search_gender == 'female' :
p_female = 1
if age_from:
age1 = 1
if age_to:
age2 = 1
if date_from:
date1 = 1
if date_to:
date2 = 1
if date1 and date2:
patient = PatientInfo.objects.filter(
Q(dateedit__range = (date_from,date_to))
)
当我选择 date_from 和 date_to 两者时仍然显示错误???即使我使用了 if request.POST.has_key('gender') 仍然错误,我也没有选择男性或女性 我是 django 的新手..请帮忙...提前感谢..
my question is when i select datefrom and dateto it showing error ."Key 'gender' not found in
now even i used the Q object still same problem as earlier..
search_gender = request.POST["gender"]
age_from = request.POST["age_from"]
age_to = request.POST["age_to"]
date_from = request.POST["date_from"]
date_to = request.POST["date_to"]
if date_from:
date_from = datetime.strptime(request.POST["date_from"],"%d %B %Y")
if date_to:
date_to = datetime.strptime(request.POST["date_to"],"%d %B %Y")
patient = PatientInfo()
p_male = 0
p_female = 0
age1 = 0
age2 = 0
date1 = 0
date2 = 0
if search_gender == 'male' :
p_male = 1
if search_gender == 'female' :
p_female = 1
if age_from:
age1 = 1
if age_to:
age2 = 1
if date_from:
date1 = 1
if date_to:
date2 = 1
if date1 and date2:
patient = PatientInfo.objects.filter(
Q(dateedit__range = (date_from,date_to))
)
still showing error when I select date_from and date_to both ??? not getting exactly even I neither select male nor female even I used if request.POST.has_key('gender') still error
and I am new to django.. plz help... thanx in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当尝试查找字典中不存在的键时,会引发您报告的错误 - 几乎正是错误告诉您的内容。
由于我所要做的就是您发布的代码,我的猜测是,无论出于何种原因,“性别”实际上并不存在于 request.POST 字典中。你需要找出原因。
一般来说,在处理字典时,最佳实践是首先检查键是否存在或使用 dict.get 方法提供后备:
The error you reported is raised when a dictionary lookup is attempted for a key that doesn't exist in that dictionary -- pretty much exactly what the error is telling you.
Since all I have to go on is the code you posted, my guess would be that for whatever reason "gender" is not actually present in the request.POST dictionary. You need to find out why.
In general, when dealing with dictionaries, the best practice is to either check for the presence of the key first or use the
dict.get
method to provide a fallback:为此,表格将非常有用!
类似于:
forms.pyviews.py
:
For this a form would be very usefull!
Something like:
forms.py
views.py: