开发者

Good practices for a flexible search page - Django

I'm jus开发者_开发技巧t 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜