Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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