3

Let say I have the following query:

query_result = Mymodel.objects.values('price').filter(price__gte=0)

If I want to generalize the query and put it in a function I could replace 'price' with a variable:

def price_query(column_name):
    query_result = Mymodel.objects.values(column_name).filter(column_name__gte=0)
    return query_result 

price_query('price')

The first replacement of 'price' with column_name works fine but how do I use the comparison __gte with a variable instead of the field name.

Any help is much appreciated.

Wessi
  • 1,702
  • 4
  • 36
  • 69

2 Answers2

11

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,256
  • 10
  • 17
-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.

Kostas Livieratos
  • 965
  • 14
  • 33
  • It's totally doable right from the filter if you use kwargs. https://stackoverflow.com/a/9122180/5892606 – evan Feb 17 '23 at 23:18