我想用一个字段过滤模型,但我想将该字段作为字符串变量传递。我该怎么做?
例如:
the_field = 'name'
TheModel.objects.filter(the_field='Gazelle')
我应该用什么替换 the_field?
最佳答案
您可以使用字典解包:
the_field = 'name'
TheModel.objects.filter(**{the_field: 'Gazelle'})
注意字典前面的两个星号 (
**
)。如果您使用 f(**{'a': 4})
调用函数,则相当于使用 f(a=4)
调用它。或者您可以使用
Q
对象,并传递一个代表键和值的 2 元组:from django.db.models import Q
the_field = 'name'
TheModel.objects.filter(Q((the_field, 'Gazelle')))
关于python - 带有字符串变量字段的 Django 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59177105/