1

I currently have this pretty standard code block in my views.py.

statsign is a form value, as well as statinput.

My model field I want to filter my queryset players by is called nba_avg_rating

if statsign == '>=' and len(statinput) > 0:
    players = players.filter(nba_avg_rating__gte=float(statinput)).order_by(sort)
elif statsign == '<=' and len(statinput) > 0:
    players = players.filter(nba_avg_rating__lte=float(statinput)).order_by(sort)
elif statsign == '=' and len(statinput) > 0:
    players = players.filter(nba_avg_rating__exact=float(statinput)).order_by(sort)

As you can see, currently my logic checks the statsign for a condition, filters by model field + the suffix, i.e. >= would result in filtering by nba_avg_rating__gte, so on and so forth.

My goal is to make this a dynamic process, in which I consolidate this process into one line. I have a field lookup dictionary like so

    field_lookup = {
    '>=': '__gte',
    '<=': '__lte',
    '=': '__exact'
}

And then I iterate through, appending the suffix to the field name, in some code like below.

for item in field_lookup.items():
    if statsign == item[0] and len(statinput) > 0:
        players = players.filter((nba_avg_rating + item[1])=float(statinput)).orderby(sort)

Now obviously the above code doesn't work, because nba_avg_rating is an expression. I can concatenate the suffix to nba_avg_rating as a string and then wrap it in eval, but alas, I then can't set the expression =flost(statinput)

Any thoughts on what I can do here?

Thanks

nick_rinaldi
  • 641
  • 6
  • 17

1 Answers1

0

According to Daniel Answer.

You can do something like:

if statsign == '>=':
    statsign = 'gte'
elif statsign == '<=':
    statsign = 'lte'
elif statsign == '=':
    statsign = 'exact'
if len(statinput) > 0:
    kwargs = {
    '{0}__{1}'.format('nba_avg_rating', statsign): float(statinput),
    }

    Person.objects.filter(**kwargs).orderby(sort)
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16