How to dynamically provide lookup field name in Django query?

Berislav Lopac picture Berislav Lopac · Aug 4, 2009 · Viewed 9.9k times · Source

I want to look for a certain string in several fields of a Model in Django. Ideally, it would go something similar to:

keyword = 'keyword'
fields = ['foo', 'bar', 'baz']
results = []
for field in fields:
    lookup = "%s__contains"
    results.append(Item.objects.filter(lookup=keyword))

Of course this won't work, as "lookup" can't be resolved into a field. Is there any other way to do this?

Answer

Botond Béres picture Botond Béres · Aug 6, 2009

I would prefer to use the Q object for something like this.

from django.db.models import Q

keyword = 'keyword'
fields = ['foo', 'bar', 'baz']

Qr = None
for field in fields:
    q = Q(**{"%s__contains" % field: keyword })
    if Qr:
        Qr = Qr | q # or & for filtering
    else:
        Qr = q

# this you can now combine with other filters, exclude etc.    
results = MyModel.objects.filter(Qr)