How to filter a QuerySet with dynamic field lookups with Python Django?

To filter a QuerySet with dynamic field lookups with Python Django, we can pass in dynamic arguments to filter.

For instance, we write

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

Person.objects.filter(**kwargs)

to unpack the kwargs dictionary as arguments for filter so we can pass in any number of arguments we want into it.

Leave a Comment

Your email address will not be published. Required fields are marked *