Good practices for a flexible search page - Django

2019-04-17 06:38发布

问题:

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?

回答1:

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.