【发布时间】:2020-08-22 10:00:39
【问题描述】:
在一个项目中,我有一个视图,它显示在浏览器中作为搜索栏来搜索食谱。我认为有比我现在做的更好的方法,但不知道如何做。如果我现在不做我正在做的事情,我会收到您无法使用 None 过滤的错误。
我知道我可以使用 try except 但没有任何值可能是 None 或引发错误。
class SearchResultListViewOther(ListView):
model = Recipe
template_name = 'recipes/search_other.html'
extra_context = {
'time': time,
'categorie': categorie,
'continent': continent,
}
def get_queryset(self):
"""
Filter out recipes by some other params like the title
"""
# Can not filter on None so set a value if no search params were given
title = self.request.GET.get('title')
if not title:
title = '0'
time_recipe = self.request.GET.get('time')
if not time_recipe:
time_recipe = 0
continent_recipe = self.request.GET.get('continent')
if not continent_recipe:
continent_recipe = '0'
object_list = Recipe.objects.filter(
Q(title__icontains=title) | Q(time__lte=time_recipe) |
Q(continent__exact=continent_recipe)
)
return object_list
【问题讨论】:
标签: python django web search django-views