[Django]-Using variable instead of field name in Django query comparions

12👍

You can unpack dictionary to provide keyword arguments:

def price_query(column_name):
    filter_kwargs = {
        "{}__gte".format(column_name): 0
    }
    query_result = Mymodel.objects.values(column_name).filter(**filter_kwargs)
return query_result
👤Kamil

-1👍

Long story short, you cannot do this.

Querysets are limited to model fields, which are the column names as you said. In fact, they operate only in database-layer, where your variables are not existent.

You will have to follow another filtering approach in order to include variables.

Leave a comment