2

I have this query:

search = request.GET['q']
Entries = Entry.objects.filter(Q(field1__icontains=search), Q(field2__icontains=search), Q(field3__icontains=search))

Is there an elegant way to make this cleaner? (I mean make somthing generic like Q(var_field__icontains=search) and the var_field will be retrived from a requested post that is one of these values field1, field2, field3).

gitaarik
  • 42,736
  • 12
  • 98
  • 105
Drwhite
  • 1,545
  • 4
  • 21
  • 44
  • 1
    @rednaw https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects – Samuele Mattiuzzo Jul 03 '13 at 11:33
  • 2
    I think it looks pretty ok as it is now. You may try this method though: http://stackoverflow.com/questions/4487054/search-multiple-fields-of-django-model-without-3rd-party-app – matino Jul 03 '13 at 11:35
  • 1
    @matino If the number of `Q` objects is fixed, don't bother with `reduce`, it would only clutter your code. Simply use `or` or `and` directly to combine the three `Q`s. – Gerard Yin Jul 03 '13 at 11:45
  • In Python 3.x reduce was moved from the standard built-in functions to the functools module. – Paulo Scardine Jul 03 '13 at 12:41
  • @matino: +1 (for the useful link) – Drwhite Jul 03 '13 at 13:55

1 Answers1

0

So, is this working for you?

search = request.GET['q']
fieldnames = ('field1', 'field2', 'field3')

filters = reduce(operator.and_, 
    (Q(**{'{}__icontains'.format(fieldname): search}) 
     for fieldname in fieldnames))

Entries = Entry.objects.filter(filters)
gitaarik
  • 42,736
  • 12
  • 98
  • 105