Django - 从字符串构建模型过滤器

DGD*_*GDD 3 python database django postgresql

是否可以使用字符串参数过滤模型?

考虑以下过滤器:

some_model.filter(parameter__gte = x)
Run Code Online (Sandbox Code Playgroud)

我想使用字符串构建该过滤器参数.

例如.

if equality == ">" and argument == x: query = "{0}__gte".format(parameter)
Run Code Online (Sandbox Code Playgroud)

然后使用该构建的参数进行过滤

some_model.filter(query = x)
Run Code Online (Sandbox Code Playgroud)

在不使用原始sql的情况下,这些行是否可行?

Pet*_*per 8

是.使用字符串作为字典的键和值,然后传递该字典以filter使用**运算符将它们用作关键字参数对.使用上面的例子:

filter_arguments = {query: x}
some_model.filter(**filter_arguments)
Run Code Online (Sandbox Code Playgroud)