问题描述
我正在进入django,这让我头疼。我试图获得一个简单的GET变量。网址是site.com/search/?q=search-term
我的观点是:
def search(request):
if request.method =='GET'and'q'in request.GET:
q = request.GET.get('q'没有)
如果q不是None:
results = Task.objects.filter(
Q(title__contains = q)
|
Q(description__contains = q)
)
... return ...
else:
...
else:
...
搜索查询,如: mysite.com/search/? (没有q)如果正确地通过第一个。
问题出在诸如 mysite.com/search/?q = 。如果q不是没有,它们不会被所捕获:
所以,简短的答案将是如何检查q ==' ? (我已经尝试过,没有,等等,没有用。)
首先,检查 request.GET
dict包含一个名为 q
的参数。你正在这样做:
if request.method =='GET'and'q'in request.GET:
接下来,检查 q
是无
或空字符串。为此,您可以这样写:
q = request.GET ['q']
如果q是不是无和q!='':
#在这里处理
请注意,不需要写 request.GET.get('q',None)
。我们已经检查过,确保 request.GET
dict中有一个'q'
键,所以我们可以直接获取价值。你应该使用 get
方法的唯一时间是,如果你不确定一个dict有一定的密钥,并且想要避免引发一个KeyError异常。
但是,根据以下事实,有一个更好的解决方案:
- 值
无
评估为False
- 空字符串
/ code>还会评估为
False
- 任何非空字符串的计算结果为
True
。
所以现在你可以写:
q = request.GET ['q']
如果q:
#在这里处理
查看这些其他资源了解更多详情:
Hey, I'm getting into django and this is getting me a headache.I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.objects.filter(
Q(title__contains=q)
|
Q(description__contains=q),
)
...return...
else:
...
else:
...
Search queries like: mysite.com/search/? (without q) gets through the first if correctly.
The problem is in queries like mysite.com/search/?q=. They don't get caught by if q is not None:
So, the short answer would be How can I check q == ''? (I've already tried '', None, etc, to no avail.)
First, check if the request.GET
dict contains a parameter named q
. You're doing this properly already:
if request.method == 'GET' and 'q' in request.GET:
Next, check if the value of q
is either None
or the empty string. To do that, you can write this:
q = request.GET['q']
if q is not None and q != '':
# Do processing here
Notice that it is not necessary to write request.GET.get('q', None)
. We've already checked to make sure there is a 'q'
key inside the request.GET
dict, so we can grab the value directly. The only time you should use the get
method is if you're not sure a dict has a certain key and want to avoid raising a KeyError exception.
However, there is an even better solution based on the following facts:
- The value
None
evaluates toFalse
- The empty string
''
also evaluates toFalse
- Any non-empty string evaluates to
True
.
So now you can write:
q = request.GET['q']
if q:
# Do processing here
See these other resources for more details:
这篇关于如何检查请求.GET var是None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!