灵活搜索页面的好习惯 - Django [英] Good practices for a flexible search page - Django
问题描述
我在Django中有一个使用过滤器的页面,以便执行搜索。
目前,我正在简单地检查GET参数,并相应地向查询器添加一个.filter():
如果颜色:
query.filter(color = color)
这感觉有点像一个丑陋的方式来做,我已经有点困惑,我怎么能使它更有活力
任何想法?
尝试:
ALLOWED =('color','size','model')
kwargs = dict(
,value)
为key,value在request.GET.items()
如果键在ALLOWED
)
query.filter(** kwargs)
这将允许您发出这样的请求 / search /?color = red& size = 1
或 / search /?model = Nikon& color = black
。
I'm just wondering if there is any example I could take from others on the topic.
I have a page within Django which uses filters, in order to perform searches.
At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accordingly:
if color:
query.filter(color=color)
This feels a bit like an ugly way to do, and I've been a bit stuck wondering how I could make it more dynamic.
Any ideas?
Try this:
ALLOWED = ('color', 'size', 'model')
kwargs = dict(
(key, value)
for key, value in request.GET.items()
if key in ALLOWED
)
query.filter(**kwargs)
This will allow you to make requests like this /search/?color=red&size=1
or /search/?model=Nikon&color=black
.
这篇关于灵活搜索页面的好习惯 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!