用p构建FIQL查询

2024-05-15 23:17:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,该函数将采用FIQL格式的字符串并返回peewee表达式。你知道吗

假设我有FIQL格式的url参数,如下所示:

fiql_str = "name==Foo,(country==USA;city==Kansas)"

使用FIQL Parser我可以取回这个对象:

['OR', ('name', '==', 'Foo'), ['AND', ('country', '==', 'USA'), ('city', '==', 'Kansas')]]

我想做的是,创建一个接受上述对象的函数,并创建一个peewee可以理解的表达式。我习惯了django & Q objects,在这里我可以像这样将表达式链接在一起:

fm = Q()
for mapping in mappings:
    fm |= Q(subscription__approver=mapping.user)
return self.filter(fm)

我试着用peewee的Query Builder / Node来模仿这个:

def map_to_filter(expressions, node):
    expression = expressions.pop(0)
    if type(expression) == str:
        if expression == "OR":
            node |= map_to_filter(expressions, node)
        if expression == "AND":
            node &= map_to_filter(expressions, node)
    elif type(expression) == tuple:
        return getattr(Store, expression[0]) + expression[1] + expression[2]
    elif type(expression) == list:
        map_to_filter(expression, node)
    return node

result = map_to_filter(expressions, peewee.Node())

但我得到了一个未实现的错误:

/lib/python3.7/site-packages/peewee.py in __sql__(self, ctx)
    616
    617     def __sql__(self, ctx):
--> 618         raise NotImplementedError
    619
    620     @staticmethod

NotImplementedError:

有可能建立这样一个功能吗?否则,还有哪些其他工具/插件可用于故障排除?你知道吗


Tags: to函数selfnodemapreturnif表达式
1条回答
网友
1楼 · 发布于 2024-05-15 23:17:39

您的问题来自于使用裸的Node,它与任何SQL都不对应(因此,没有SQL方法)。你知道吗

我建议累积一个列表并使用functools.reduce()来组合它们。你知道吗

例如

list_of_conds = [
    (model.field1 == 'val1'),
    (model.field2 == 'bar')]
reduce(operator.and_, list_of_conds)

您可以将reduce函数切换为操作员或如有必要,继续使用深度优先搜索。你知道吗

相关问题 更多 >