How do I use a string as a keyword argument?

Python

Python Problem Overview


Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go

from gblocks.models import Image
f = 'image__endswith="jpg"' # Would be scripted in another area, but passed as text <user input>
d = Image.objects.filter(f)


#for the non-django pythonistas:
d = Image.objects.filter(image__endswith="jpg")
# would be the non-dynamic equivalent.

Python Solutions


Solution 1 - Python

d = Image.objects.filter(**{'image__endswith': "jpg"})

Solution 2 - Python

You'd need to split out the value from the keyword, then set up a dict using the keyword as the key, and the value as the value. You could then use the double-asterisk function paramater with the dict.

So...

keyword, sep, value = f.partition('=')
kwargs = {keyword: value.strip('"')}
d = Image.objects.filter(**kwargs)

Note, this code assumes that there won't be any equals signs '=' in the keyword (they'll only be used to separate the keyword from the value), and the value will be wrapped in quotes.

Solution 3 - Python

The eval option should work fine, as long as you wrap it around the entire expression, not just the f:

f = 'image__endswith="jpg"'
d = eval('Image.objects.filter(' + f + ')')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIssac KellyView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonJosh WrightView Answer on Stackoverflow
Solution 3 - PythonMarcelo CantosView Answer on Stackoverflow