开发者

Django query parameters not returning None

I have a few lines of code in my view that get a query param and then filter based on that parameter.

search = request.GET.get('search', None)

if search:
    accounts = UserProfile.objects.filter(fullname__icontains=search).order_by('fullname')
else:
    accounts = UserProfile.objects.all().order_by('fullname')

For some odd reason, on my local machine, it appears that when I give a url of something like localhost/accounts/admin/ or localhost/accounts/admin/?search= it works fine -- on my production server, however, it seems to think that the search is an empty string, and then it passes the if/then conditional which returns an empty queryset. GET:<QueryDict: {u'search': [u'']}>

Why d开发者_JS百科oes python seem to think that this empty string is "something?"

>>> x = ''
>>> if x:
...     print "Exists"
... else:
...     print "None"
... 
None

>>> x = u''
>>> if x:
...     print "exists"
... else:
...     print "None"
... 
None


Actually if you pay close attention the search variable is set to a list that contain an empty unicode string [u''] so that why it's evaluated to True:

>>> search = [u'']
>>> bool(search)
True

And for why you are seeing different behavior between your test and production sadly i'm not sure why !? maybe the doc can help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜