Good practices for a flexible search page - Django

最后都变了- 提交于 2019-12-22 01:17:40

问题


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.



来源:https://stackoverflow.com/questions/3202922/good-practices-for-a-flexible-search-page-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!