views:

61

answers:

1

Hi folks,

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?

+5  A: 

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.

Alexander Artemenko
@Alexander: no way! this is great! Can you use dicts with any function, by using the method you just shown me?
RadiantHex
@Alexander: any suggestions for DateTime?
RadiantHex
You can, but you can't use international characters as keyword argument's names, if you want to do this, you should use this syntax: def test(**kwargs): param = kwargs['параметр'] # do something.
Alexander Artemenko
For date-time you need to add parsing. Use http://pypi.python.org/pypi/python-dateutil/1.5 for this. The code will be a little more complex.
Alexander Artemenko