我有一些代码包含了以下几行的搜索功能:
def searchHay(request):
content = sorted(request.GET.getlist('content', ''))
sqs = SearchQuerySet().facet('this').facet('that').facet('the_other')
# This if/else block is perhaps not a very good solution...
if "things" in content and "stuff" in content:
sqs = sqs.models(Things, Stuff)
elif "things" in content:
sqs = sqs.models(Things)
elif "stuff" in content:
sqs = sqs.models(Stuff)
sqs = sqs.order_by('sort_field')
view = search_view_factory(
view_class=FacetedSearchView,
template='search/search.html',
searchqueryset=sqs,
form_class=AllFacetedSearchForm
)
return view(request)
如您所见,根据用户在提交表单时选择的某些选项搜索不同的模型,这些选项在此处作为“内容”传递。这有效,但随着模型数量的增加变得非常麻烦。如果有人对更优雅的方式有任何建议,那么我很想知道它们是什么。
答案 0 :(得分:1)
一个简单的解决方案可能是“独立的ifs ”,而不是:
# This if/else block is perhaps not a very good solution...
if "things" in content and "stuff" in content:
sqs = sqs.models(Things, Stuff)
elif "things" in content:
sqs = sqs.models(Things)
elif "stuff" in content:
sqs = sqs.models(Stuff)
你可以:
if "things" in content:
sqs = sqs.models(Things)
if "stuff" in content:
sqs = sqs.models(Stuff)
如果有things
&成功,您无需管理“多项选择”。内容stuff
,它会自动添加两个过滤器。如果您将来需要添加更多模型,只需为每个模型添加一个模型。
我想如果你sqs = sqs.models(Things)
然后sqs = sqs.models(Stuff)
结果将是0或空但是......
我在控制台中对它进行了测试,以确保我的惊喜......
sqs = sqs.models(Things)
sqs.count()
< - 此返回让我们说100 sqs = sqs.models(Stuff)
sqs.count()
< - 这将返回100 +模型Stuff的对象 所以你可以拥有独立的ifs,并且它会按照你的预期工作,因为你好像这样做:
sqs = sqs.models(Things)
sqs = sqs.models(Stuff)
与sqs.models(Things, Stuff)