How do I use a string as a keyword argument?

后端 未结 3 1682
眼角桃花
眼角桃花 2020-12-08 00:24

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, bu

相关标签:
3条回答
  • 2020-12-08 00:44
    d = Image.objects.filter(**{'image__endswith': "jpg"})
    
    0 讨论(0)
  • 2020-12-08 00:51

    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 + ')')
    
    0 讨论(0)
  • 2020-12-08 00:55

    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.

    0 讨论(0)
提交回复
热议问题