> if (search_query['organisation']!=""): > jobs = jobs.filter(organisation=search_query['organisation']) > if (search_query['region']!=""): > jobs = jobs.filter(region=search_query['region']) > if (search_query['category']!=""): > jobs = jobs.filter(category=search_query['category']) > > and I want to remove the redundancy - what's a nice idiomatic Django > way to do it?
given that the field-name and key match exactly, you could do something like for field in ('organisation', 'region', 'category'): if search_query[field].strip(): jobs = jobs.filter(**{field: search_query[field]}) which minimizes the repetition. I like to add the strip() just so it tidies the incoming value. You might even change that one line to something like if search_query.get(field, '').strip(): so that in the event that not all the fields are included in the request, it still behaves sensibly. If you need to do a django-ish manipulation on it, such as "__icontains", you can simply add it in the mapping: jobs = jobs.filter(**{ field + '__icontains': search_query[field] }) Or, if needed, your iterator loop can provide field-specific modifiers: fields_and_modifiers = ( ('organisation', 'icontains'), ('region', 'iexact'), ('category', 'icontains'), ) for field, modifier in fields_and_modifiers: if search_query.get(field, '').strip(): jobs = jobs.filter(**{ field + '__' + modifier: search_query[field] }) All sorts of delightful tricks lurk in Django's ORM and Python's keyword-expansion. -tim --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---