In Django, how does one filter a QuerySet with dynamic field lookups?

Python’s argument expansion may be used to solve this problem:

kwargs = {
    '{0}__{1}'.format('name', 'startswith'): 'A',
    '{0}__{1}'.format('name', 'endswith'): 'Z'
}

Person.objects.filter(**kwargs)

This is a very common and useful Python idiom.

Leave a Comment