4

I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.

field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)

where if funct() returns name would equal to

locations = Locations.objects.filter(name__lte=arg1)

Not sure how to do that ...

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
philgo20
  • 6,337
  • 6
  • 34
  • 43

1 Answers1

11

You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments:

field_name = funct()
params = {field_name + '__lte': arg1,       # field_name should still contain string
          'some_other_field_name': arg2}

locations = Locations.objects.filter(**params)

# is the same as (assuming field_name = 'some_name'):
# Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)
T. Stone
  • 19,209
  • 15
  • 69
  • 97
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143